gpt4 book ai didi

javascript - parseFloat ('4.2.2' ) 产生 4.2 而不是 NaN?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:57:20 24 4
gpt4 key购买 nike

我在尝试破解我的代码时发现了这种意外行为...有人可以向我解释为什么会这样吗以及应该如何确保提供的值是真正的 float ?

例如:

alert(parseFloat('4.2.2'));

我期待的是NaN...不是我得到的。

我做了一个非常简单的jsfiddle演示here .

最佳答案

这就是 parseFloatparseInt 方法的工作原理。它们解析到输入无效的程度。仅当第一个字符无效时,它们才返回 NaN..


引用https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseFloat

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.

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


要检查字符串是否为数字,您可以使用(来自 Validate decimal numbers in JavaScript - IsNumeric() )

function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}

关于javascript - parseFloat ('4.2.2' ) 产生 4.2 而不是 NaN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15042764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com