当字符串包含非数字字符时,parseFloat()如何工作? [英] How does parseFloat() work when the string contains non-numeric characters?

查看:154
本文介绍了当字符串包含非数字字符时,parseFloat()如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行 parseFloat()时遇到问题-我不明白为什么它会产生以下输出:

I'm having a problem when executing parseFloat() - I don't understand why it produces the following outputs:

document.write(parseFloat("6e2") + "<br />"); //output is 600 why?
document.write(parseFloat("6b2") + "<br />"); //output is 6 why?
document.write(parseFloat("6c2") + "<br />"); //output is 6 why?

您能告诉我如何

推荐答案

6e2 会产生600,因为它正在处理您的输入

6e2 produces 600 because it's treating your input as scientific notation.

6e2 == 6 x 10 2 == 600

6e2 == 6 x 102 == 600

另外两个产生6,因为 parseFloat 解析6,然后输入它无法转换为数字,所以它停止并返回找到的结果

The other two produce 6 because parseFloat parses the 6, then gets to input it isn't able to convert to a number, so it stops, and returns the result found so far.

每个 MDN


parseFloat是一个顶层函数,与任何
对象都没有关联。

parseFloat is a top-level function and is not associated with any object.

parseFloat解析其参数(字符串),并返回浮点数
数字。如果遇到除符号(+或-),
数字(0-9),小数点或指数以外的字符,它将返回值
到该点为止,并忽略该字符以及所有后续的
个字符。

parseFloat parses its argument, a string, and returns a floating point number. If it encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters. Leading and trailing spaces are allowed.

如果第一个字符不能转换为数字,则parseFloat
将返回NaN。

If the first character cannot be converted to a number, parseFloat returns NaN.

出于算术目的,NaN值不是任何基数的数字。
您可以调用isNaN函数来确定
parseFloat的结果是否为NaN。如果将NaN传递给算术运算,则
运算结果也将为NaN。

For arithmetic purposes, the NaN value is not a number in any radix. You can call the isNaN function to determine if the result of parseFloat is NaN. If NaN is passed on to arithmetic operations, the operation results will also be NaN.

这篇关于当字符串包含非数字字符时,parseFloat()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆