?????? ?????? ???? ?????????? ?? ???????????? ???? ?? ???????????? ?????? ?????????????? ???? ???? ?????? ???????????? ???????? ?????????
It’s always safe to convert a number into a string, because that operation can’t fail. The reverse task—converting a string into a number, so you can use it in calculations—is a more delicate affair.
By using ????????????():
The Number() function won’t accept formatting like currency symbols and comma separators. It will allow extra spaces at the beginning and end of the string.
The Number() function also converts empty strings or strings with only whitespace to the number 0. This might be a reasonable default (for example, if you’re retrieving user input from a text box), but it’s not always appropriate. If a conversion fails, the Number() function assigns the value NaN (for not a number) to your variable.
By using ????????????????????():
An alternate approach is to use the parseFloat() method. It’s a slightly looser conversion that tolerates text after the number. However, parseFloat() is stricter with blank strings, which it refuses.
Sometimes Developers use some conversion tricks that are functionally equivalent to the Number() function, like multiplying a string by 1 (numberInString*1) or using the unary operator (+numberInString). But using Number() or parseFloat() is preferred for clarity.
领英推荐
???????????? ???? ?????????? ????????????() ?????? ????????????????????():
If you have a formatted number (like 4,500), you need to do more work to convert it. The Number() method will return NaN, and parseFloat() will stop at the comma and treat it as 4.
Unfortunately, although JavaScript has an Intl.NumberFormat object that can create formatted strings from numbers. However, it doesn’t provide parsing functionality for the reverse operation.
We can use regular expressions to take care of tasks like removing commas from a string. But a home brew solution can be risky, because some locales use commas to separate thousands, while others use them to separate decimals. In situations like these, a well-used, well-tested JavaScript library like Numeral.js(https://numeraljs.com/) is a better choice.
Numeral.js is a js library inspired by Moment.js that format and manipulate numbers to look like currency, percentages, times, or even plain old numbers with decimal places, thousands, and abbreviations. #javascript #frontenddeveloper #javascriptdevelopers #es6
image source: ????????????????