在许多情况下,toFixed()失败是因为javascript数学中浮点。
我找到了这个解决方案:
function toFixed(decimalPlaces) {
var factor = Math.pow(10, decimalPlaces || 0);
var v = (Math.round(Math.round(this * factor * 100) / 100) / factor).toString();
if (v.indexOf('.') >= 0) {
return v + factor.toString().substr(v.length - v.indexOf('.'));
}
return v + '.' + factor.toString().substr(1);
}还有这个:
function toFixed(num, fixed) {
var re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fixed || -1) + '})?');
return num.toString().match(re)[0];
}还有其他方法吗?我必须确定它在任何情况下都表现得很好。在边缘情况下也是如此。
编辑:https://github.com/MikeMcl/decimal.js @Tschallacka
Number.prototype.toFixed = function(fixed) {
x = new Decimal(Number(this));
return x.toFixed(fixed);
};发布于 2017-01-18 18:37:10
我建议你使用一个库:
https://github.com/MikeMcl/decimal.js
在处理金融数据时,我发现它非常可靠。
处理浮点数总是很困难,但有几种解决方案。我建议你使用一个维护得很好的现有库,这个库已经被拔掉了乳牙。
假设您添加了decimal.js,您可以根据财务价值执行此操作。
/**
* @var input float
*/
function toFixed(input) {
var dec = new Decimal(input);
return dec.toFixed(2);
}
console.log("float to fixed 2 decimal places: ",toFixed(200.23546546546));
function toFixed2(decimalPlaces) {
var dec = new Decimal(1);
return dec.toFixed(decimalPlaces);
}
console.log("get a fixed num: ",toFixed2(10));
Number.prototype.toFixed = function(fixed) {
x = new Decimal(Number(this));
return x.toFixed(fixed);
};
var num = new Number(10.4458);
console.log("Number to fixed via prototyped method: ",num.toFixed(2));
var x = 44.456
console.log('Number to fixed via inderect number casting:' ,x.toFixed(2));<script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/7.1.1/decimal.min.js"></script>
https://stackoverflow.com/questions/41717035
复制相似问题