我在Javascript中有两个浮点数,具有高精度和低精度(事先不知道),例如:
1545.165
12.15364613
如何将高精度数字舍入到与精度较低的数字相同的精度? 在我们的情况下
12.154
答案 0 :(得分:2)
您可以使用toFixed()
函数进行争论。
语法: <number>.toFixed(precision)
例如:
12.15364613.toFixed(3)
提供12.154
但是为了让它适合你的情况,你想做这样的事情:
警告未经测试的代码,我只是想让您大致了解如何做到这一点,当然下面的代码可以改进。
var num1 = 12.15364613;
var num1Str = (12.15364613).toString();
var num1Precision = parseInt(num1Str.substring(num1Str.indexOf('.')).length - 1);
var num2 = 12.154;
var num2Str = (12.154).toString();
var num2Precision = parseInt(num2Str.substring(num2Str.indexOf('.')).length - 1);
if(num1Precision > num2Precision){
num1 = num1.toFixed(num2Precision);
} else{
num2 = num2.toFixed(num1Precision);
}
答案 1 :(得分:1)
纯数学解决方案
为了获得未知数字(变量)的精度,你可以使用这样一个函数:
function getPrecision(x) {
// i < 10 - just to avoid infinite looping
// (which may occur if x is a real number like PI)
// x - Math.floor(x) + (x < 0? 1 : 0) is a fractional part of x
for (var i = 0; i < 10 && x - Math.floor(x) + (x < 0? 1 : 0) > 0; i++, x *= 10) ;
return i;
}
所以代码应该是这样的:
// array of given numbers:
aVals = [1545.165, 12.15364613];
// array of numbers' precisions:
var aPre = aVals.map(getPrecision);
// find the least precision:
var minPre = Math.min.apply(null, aPre);
// result array of fixed numbers with the same precision:
var aValsFixed = aVals.map(function(v) { return v.toFixed(minPre); });
答案 2 :(得分:0)
你的意思是这样的吗?
var number = 1.2333445454;
var n = number.toFixed(3);
alert(n);