Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

angular - JavaScript function parseFloat() fails for negative values in certain locales

While working with locale translation and parsing decimal numbers from text to numerical values in Angular 10, I came across the following problem:

Consider the string value value = "-35.17 %". I want to convert this a numerical value using parseFloat(value). This works fine for application locale en-US.

However, if the user changes application locale to nb-NO (Norwegian), the parsing fails, resulting in a NaN.

The reason for this is that the Norwegian locale uses a different character for the negative prefix (? instead of -).

The workaround for this particular issue is simple, by performing a .replace("?", "-") on the string before parsing, but shouldn't JavaScript be able to handle parsing of both these characters? Is it only safe to perform parsing on locale en-US?

question from:https://stackoverflow.com/questions/65601940/javascript-function-parsefloat-fails-for-negative-values-in-certain-locales

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The JavaScript function parseFloat() needs an input string that meets certain requirements, including (but not limited to) the following:

  • If parseFloat encounters a character other than a plus sign (+), minus sign (- U+002D HYPHEN-MINUS), numeral (0–9), decimal point (.), or exponent (e or E), it returns the value up to that character, ignoring the invalid character and characters following it.

Localized strings may contain characters that does not meet those requirements.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...