你能四舍五入一个数字在javascript小数点后1个字符(适当四舍五入)?

我尝试了*10,四舍五入,/10,但它在int的末尾留下了两个小数。


当前回答

var number = 123.456;

console.log(number.toFixed(1)); // should round to 123.5

其他回答

数学。整数(num * 10) / 10无效。

例如,1455581777.8-145558160.4会得到1310023617.3999999。

所以只使用num。tofixed (1)

试试这个:

var original=28.453

// 1.- round "original" to two decimals
var result = Math.round (original * 100) / 100  //returns 28.45

// 2.- round "original" to 1 decimal
var result = Math.round (original * 10) / 10  //returns 28.5

// 3.- round 8.111111 to 3 decimals
var result = Math.round (8.111111 * 1000) / 1000  //returns 8.111

不那么复杂,更容易实现……

有了这个,你可以创建一个函数来做:

function RoundAndFix (n, d) {
    var m = Math.pow (10, d);
    return Math.round (n * m) / m;
}

函数RoundAndFix (n, d) { var m =数学。Pow (10, d); 返回数学。圆(n * m) / m; } console.log (RoundAndFix(8.111111, 3));

编辑:看这个如何四舍五入使用四舍五入一半。四舍五入模式是我们大多数人在小学时学到的

使用toprecprecision方法:

var a = 1.2345
a.toPrecision(2)

// result "1.2"

这似乎对我抛出的任何东西都有效:

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

如果你的源代码是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;
}