CommunityVilx-提出了一个问题:What is the decimal separator symbol in JavaScript?,或许与您遇到的问题类似。
回答者Andy E给出了该问题的处理方式:
According to the specification, a DecimalLiteral is defined as:
DecimalLiteral :: DecimalIntegerLiteral . DecimalDigitsopt ExponentPartopt . DecimalDigits ExponentPartopt DecimalIntegerLiteral ExponentPartopt
and for satisfying the parseFloat argument:
- Let inputString be ToString(string).
- Let trimmedString be a substring of inputString consisting of the leftmost character that is not a StrWhiteSpaceChar and all characters to the right of that character.(In other words, remove leading white space.)
- If neither trimmedString nor any prefix of trimmedString satisfies the syntax of a StrDecimalLiteral (see 9.3.1), return NaN.
- Let numberString be the longest prefix of trimmedString, which might be trimmedString itself, that satisfies the syntax of a StrDecimalLiteral.
- Return the Number value for the MV
So numberString becomes the longest prefix of trimmedString that satisfies the syntax of a StrDecimalLiteral, meaning the first parseable literal string number it finds in the input. Only the .
can be used to specify a floating-point number. If you're accepting inputs from different locales, use a string replace:
function parseLocalNum(num) { return +(num.replace(",", ".")); }
The function uses the unary operator instead of parseFloat because it seems to me that you want to be strict about the input. parseFloat("1ABC")
would be 1
, whereas using the unary operator +"1ABC"
returns NaN
. This makes it MUCH easier to validate the input. Using parseFloat is just guessing that the input is in the correct format.
希望本文对你有帮助,欢迎支持JavaScript中文网
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/24951