如何使用 Javascript 使浮点数的精度相同
How to make the precision of float numbers the same using Javascript
我在 Javascript 中有两个精度高和精度低的浮点数(事先不知道)例如:
1545.165
12.15364613
如何将高精度数字四舍五入到与低精度数字相同的精度?
在我们的例子中
12.154
你可以用 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);
}
你的意思是这样的?
var number = 1.2333445454;
var n = number.toFixed(3);
alert(n);
纯数学解
为了获得未知数(变量)的精度,您可以使用这样的函数:
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); });
我在 Javascript 中有两个精度高和精度低的浮点数(事先不知道)例如:
1545.165
12.15364613
如何将高精度数字四舍五入到与低精度数字相同的精度? 在我们的例子中
12.154
你可以用 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);
}
你的意思是这样的?
var number = 1.2333445454;
var n = number.toFixed(3);
alert(n);
纯数学解
为了获得未知数(变量)的精度,您可以使用这样的函数:
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); });