将 JavaScript 字符串变量转换为十进制/金钱

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6095795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:13:29  来源:igfitidea点击:

convert a JavaScript string variable to decimal/money

javascriptdecimalstring-conversion

提问by Varada

How can we convert a JavaScript string variable to decimal?

我们如何将 JavaScript 字符串变量转换为十进制?

Is there a function such as:

有没有这样的功能:

parseInt(document.getElementById(amtid4).innerHTML)

回答by lonesomeday

Yes -- parseFloat.

是的—— parseFloat

parseFloat(document.getElementById(amtid4).innerHTML);


For formattingnumbers, use toFixed:

格式化数字,请使用toFixed

var num = parseFloat(document.getElementById(amtid4).innerHTML).toFixed(2);

numis now a string with the number formatted with two decimal places.

num现在是一个字符串,其数字格式为两位小数。

回答by KooiInc

You can also use the Numberconstructor/function (no need for a radix and usable for both integers and floats):

您还可以使用Number构造函数/函数(不需要基数并且可用于整数和浮点数):

Number('09'); /=> 9
Number('09.0987'); /=> 9.0987

Alternatively like Andy E said in the comments you can use +for conversion

或者像 Andy E 在评论中所说的那样,您可以+用于转换

+'09'; /=> 9
+'09.0987'; /=> 9.0987

回答by Sanjay

This works:

这有效:

var num = parseFloat(document.getElementById(amtid4).innerHTML, 10).toFixed(2);

回答by zloctb

var formatter = new Intl.NumberFormat("ru", {
  style: "currency",
  currency: "GBP"
});

alert( formatter.format(1234.5) ); // 1 234,5 £

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

回答by dondrzzy

It is fairly risky to rely on javascript functions to compare and play with numbers. In javascript (0.1+0.2 == 0.3) will return false due to rounding errors. Use the math.js library.

依靠 javascript 函数来比较和玩数字是相当冒险的。在 javascript (0.1+0.2 == 0.3) 中,由于舍入错误,将返回 false。使用 math.js 库。

回答by sidonaldson

I made a little helper function to do this and catch all malformed data

我做了一个小辅助函数来做到这一点并捕获所有格式错误的数据

function convertToPounds(str) { 
    var n = Number.parseFloat(str);
    if(!str || isNaN(n) || n < 0) return 0;
    return n.toFixed(2);
}

Demo is here

演示在这里

回答by Tushar Sagar

An easy short hand way would be to use +x It keeps the sign intact as well as the decimal numbers. The other alternative is to use parseFloat(x). Difference between parseFloat(x) and +x is for a blank string +x returns 0 where as parseFloat(x) returns NaN.

一个简单的简写方法是使用 +x 它保持符号和十进制数完好无损。另一种选择是使用 parseFloat(x)。parseFloat(x) 和 +x 之间的区别在于空白字符串 +x 返回 0,而 parseFloat(x) 返回 NaN。