Home >Web Front-end >JS Tutorial >How to convert value to floating point number in javascript

How to convert value to floating point number in javascript

青灯夜游
青灯夜游Original
2021-09-07 16:00:338061browse

In JavaScript, you can use the parseFloat() method to convert a value to a floating point number. This method can parse a string and return a floating point number. The specific syntax is "parseFloat(string)".

How to convert value to floating point number in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

javascript converts the value to a floating point number

In javascript, you can use the parseFloat() method to convert the value As a floating point number, it can parse a string and return a floating point number.

parseFloat() is also a global method, it can convert the value to a floating point number, that is, it can identify the first occurrence decimal point, and the second decimal point is considered illegal.

This function specifies whether the first character in the string is a number. If it is, the string is parsed until it reaches the end of the number, and the number is returned as a number rather than as a string.

The conversion process is as follows:

  • First parse the character at position 0. If it is not a valid number, NaN will be returned directly.

  • If the character at position 0 is a number or can be converted to a valid number, continue to parse the character at position 1. If it is not a valid number, return the valid character at position 0 directly. number.

  • And so on, analyzing each character one by one from left to right until a non-numeric character is found.

  • parseFloat() will convert all legal numeric characters analyzed previously into numerical values ​​and return them.

console.log(parseFloat("1.234.5"));  //返回数值 1.234

The parameter of parseFloat() must be a string in decimal form, and octal or hexadecimal numeric strings cannot be used. At the same time, 0 (octal number identification) in front of the number will be ignored, and 0 will be returned for hexadecimal numbers.

console.log(parseFloat("123"));  //返回数值 123
console.log(parseFloat("123abc"));  //返回数值 123
console.log(parseFloat("010"));  //返回数值 10
console.log(parseFloat("0x10"));  //返回数值 0
console.log(parseFloat("x10"));  //返回数值 NaN

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to convert value to floating point number in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn