Below, I have a number which I am trying to format using javascript. But it returns NaN.
var v = "153,452.47";
alert(Math.round(v));
You can use following fiddle: Example
How can we format a numeric string having separators?
Below, I have a number which I am trying to format using javascript. But it returns NaN.
var v = "153,452.47";
alert(Math.round(v));
You can use following fiddle: Example
How can we format a numeric string having separators?
我认为这会很好用
var v = "153,452.47";
var float = parseFloat(v.replace(/[^0-9.]/g, ''));
// => 153452.47
如果要四舍五入为整数
var v = "153,452.47";
float.toFixed(0);
// => 153452
让我们做一个不错的小功能!
var roundFormattedNumber = function(n){
var result = parseFloat(n.replace(/[^0-9.]/g, ''));
return isNaN(result) ? NaN : result.toFixed(0);
};
这比提供的其他解决方案效果更好,因为它是白名单正则表达式替换而不是黑名单替换。这意味着它甚至适用于像这样的数字$ 1,234.56
提供的其他解决方案不适用于这些数字
roundFormattedNumber("$ 123,456,489.00");
//=> 123456789
roundFormattedNumber("999.99 USD");
//=> 1000
roundFormattedNumber("1 000 €");
//=> 1000
roundFormattedNumber("i like bears");
//=> NaN
您必须删除逗号。
parseFloat("153,452.57".replace(/,/g,"")).toFixed(0);
如果你想要 2 位小数:
parseFloat("153,452.57".replace(/,/g,"")).toFixed(2);
尝试这个
var v = "153,452.47";
Math.round(parseFloat(v.replace(",","")));