你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?
我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。
当前回答
如果你的方法不起作用,请发布你的代码。
然而,你可以完成舍入任务如下:
var value = Math.round(234.567*100)/100
234.56英镑可以吗
类似的
var value = Math.round(234.567*10)/10
会给出234.5
通过这种方式,您可以使用一个变量来代替前面使用的常量。
其他回答
var num = 34.7654;
num = Math.round(num * 10) / 10;
console.log(num); // Logs: 34.8
如果你的源代码是typescript,你可以使用这样的函数:
public static ToFixedRounded(decimalNumber: number, fractionDigits: number): number {
var rounded = Math.pow(10, fractionDigits);
return (Math.round(decimalNumber * rounded) / rounded).toFixed(fractionDigits) as unknown as number;
}
这似乎对我抛出的任何东西都有效:
function round(val, multiplesOf) {
var s = 1 / multiplesOf;
var res = Math.ceil(val*s)/s;
res = res < val ? res + multiplesOf: res;
var afterZero = multiplesOf.toString().split(".")[1];
return parseFloat(res.toFixed(afterZero ? afterZero.length : 0));
}
它是四舍五入的,所以您可能需要根据用例修改它。这应该可以工作:
console.log(round(10.01, 1)); //outputs 11
console.log(round(10.01, 0.1)); //outputs 10.1
我找到了一个避免精度问题的方法:
function badRound (num, precision) {
const x = 10 ** precision;
return Math.round(num * x) / x
}
// badRound(1.005, 2) --> 1
function round (num, precision) {
const x = 10 ** (precision + 1);
const y = 10 ** precision;
return Math.round(Math.round(num * x) / 10) / y
}
// round(1.005, 2) --> 1.01
完成最佳答案:
var round = function ( number, precision )
{
precision = precision || 0;
return parseFloat( parseFloat( number ).toFixed( precision ) );
}
输入参数number可能"not"总是一个数字,在这种情况下。tofixed不存在。