Get the App
SLTechnology News&Howtos  ›  Development  › 

How to convert an es6 string to a number

Shulou Source: shulou.com Published: 2022-06-03 16:05:26 11月14日 Update

In this issue, the editor will bring you about how to convert es6 strings into numbers. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

Conversion methods: 1, use parseInt () to convert a string to an integer, syntax "parseInt (" string ")"; 2, use parseFloat () to convert a string into a floating point number, syntax "parseFloat (" string ")"; 3, use multiplication operator, syntax "numeric string * 1".

The operating environment of this tutorial: windows7 system, ECMAScript version 6, Dell G3 computer.

Method 1: convert to an integer using parseInt ()

Console.log (parseInt ("12345red")); / / return 12345console.log (parseInt ("0xA")); / / return 10console.log (parseInt ("56.9")); / / return 56console.log (parseInt ("red")); / / return NaNconsole.log (parseInt ("AF", 16)); / / return 175console.log (parseInt ("10", 2)); / / return 2console.log (parseInt ("10", 8)) / / return 8console.log (parseInt ("10", 10)); / / return 10 beat / if the decimal number contains a leading 0, it is better to use cardinality 10, so that you don't accidentally get the octal value console.log (parseInt ("010")); / / return 8console.log (parseInt ("010", 8)); / / return 8console.log (parseInt ("010", 10); / / return 10

Output result:

Method 2: use parseFloat () to convert to a floating point number

Console.log (parseFloat ("12345red")); / / return 12345console.log (parseFloat ("0xA")); / / return NaNconsole.log (parseFloat ("11.2")); / / return 11.2console.log (parseFloat ("11.22.33")); / / return 11.22console.log (parseFloat ("0102")); / / return 102console.log (parseFloat ("red")); / / return NaN

Output result:

Method 3: use the multiplication operator

If the variable is multiplied by 1, the variable is automatically converted to a numeric value by JavaScript. After multiplying 1, the result does not change, but the type of the value is converted to a numeric value. Returns NaN if the value cannot be cached to a legal value.

Var a = 1; / numeric var b = "1"; / / numeric string console.log (a + (b * 1)); / / return numerical value 2 above is how to convert the es6 string into numbers shared by the editor. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Tags: Characters strings numeric values numbers methods results syntax multiplication signs contents variables integers points operators analysis output operations legal professional small and medium octal Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Docker macOS NVidia Microsoft