# 如何在JavaScript中舍入到小数点后1位？

2020/09/28 22:21 · javascript ·  · 0评论

`Math.round(num * 10) / 10` 有效，这是一个示例...

``````var number = 12.3456789
var rounded = Math.round(number * 10) / 10
// rounded is 12.3
``````

``````var fixed = rounded.toFixed(1)
// fixed is always to 1 d.p.
// NOTE: .toFixed() returns a string!

// To convert back to number format
parseFloat(number.toFixed(2))
// 12.34
// but that will not retain any trailing zeros

// So, just make sure it is the last step before output,
// and use a number format during calculations!
``````

### 编辑：添加具有精度功能的回合...

``````function round(value, precision) {
var multiplier = Math.pow(10, precision || 0);
return Math.round(value * multiplier) / multiplier;
}
``````

...用法...

``````round(12345.6789, 2) // 12345.68
round(12345.6789, 1) // 12345.7
``````

...默认舍入到最接近的整数（精度0）...

``````round(12345.6789) // 12346
``````

...并且可以四舍五入到最接近的10或100等...

``````round(12345.6789, -1) // 12350
round(12345.6789, -2) // 12300
``````

...以及正确处理负数...

``````round(-123.45, 1) // -123.4
round(123.45, 1) // 123.5
``````

...并可以与toFixed组合以一致地格式化为字符串...

``````round(456.7, 2).toFixed(2) // "456.70"
``````
``````var number = 123.456;

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

``````(Math.round(5.01 * 10) / 10).toFixed(1)
``````

``````function roundedToFixed(_float, _digits){
var rounded = Math.pow(10, _digits);
return (Math.round(_float * rounded) / rounded).toFixed(_digits);
}
``````

`lodash`有一个`round`方法：

``````_.round(4.006);
// => 4

_.round(4.006, 2);
// => 4.01

_.round(4060, -2);
// => 4100
``````

``````var rounded = ((num * 10) << 0) * 0.1;
``````

``````var rounded = (num + '').replace(/(^.*?\d+)(\.\d)?.*/, '\$1\$2');
``````

``````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;
}
``````

``````let myNumber = 213.27321;
+myNumber.toFixed(1); // => 213.3
``````
1. toFixed：使用定点符号返回表示给定数字的字符串。
2. 一元加号（+）：一元加号运算符位于其操作数之前，并求值为其操作数，但尝试将其转换为数字（如果尚未转换为数字）。

``````var a = 1.2345
a.toPrecision(2)

// result "1.2"
``````
``````var num = 34.7654;

num = Math.round(num * 10) / 10;

console.log(num); // Logs: 34.8
``````

``````var round = function ( number, precision )
{
precision = precision || 0;
return parseFloat( parseFloat( number ).toFixed( precision ) );
}
``````

ES 6版本的接受答案：

``````function round(value, precision) {
const multiplier = 10 ** (precision || 0);
return Math.round(value * multiplier) / multiplier;
}
``````

`inconsistency`在四舍五入可能引入防不胜防，在客户端代码中的bug。

``````function naiveRound(num, decimalPlaces) {
var p = Math.pow(10, decimalPlaces);
return Math.round(num * p) / p;
}

console.log( naiveRound(1.245, 2) );  // 1.25 correct (rounded as expected)
console.log( naiveRound(1.255, 2) );  // 1.25 incorrect (should be 1.26)``````

``````/**
* Round half up ('round half towards positive infinity')
* Uses exponential notation to avoid floating-point issues.
* Negative numbers round differently than positive numbers.
*/
function round(num, decimalPlaces) {
num = Math.round(num + "e" + decimalPlaces);
return Number(num + "e" + -decimalPlaces);
}

// test rounding of half
console.log( round(0.5, 0) );  // 1
console.log( round(-0.5, 0) ); // 0

// testing edge cases
console.log( round(1.005, 2) );   // 1.01
console.log( round(2.175, 2) );   // 2.18
console.log( round(5.015, 2) );   // 5.02

console.log( round(-1.005, 2) );  // -1
console.log( round(-2.175, 2) );  // -2.17
console.log( round(-5.015, 2) );  // -5.01``````

``````// Round half away from zero
function round(num, decimalPlaces) {
num = Math.round(Math.abs(num) + "e" + decimalPlaces) * Math.sign(num);
return Number(num + "e" + -decimalPlaces);
}
``````

``````/**
* Round half away from zero ('commercial' rounding)
* Uses correction to offset floating-point inaccuracies.
* Works symmetrically for positive and negative numbers.
*/
function round(num, decimalPlaces) {
var p = Math.pow(10, decimalPlaces);
var e = Number.EPSILON * num * p;
return Math.round((num * p) + e) / p;
}

// test rounding of half
console.log( round(0.5, 0) );  // 1
console.log( round(-0.5, 0) ); // -1

// testing edge cases
console.log( round(1.005, 2) );  // 1.01
console.log( round(2.175, 2) );  // 2.18
console.log( round(5.015, 2) );  // 5.02

console.log( round(-1.005, 2) ); // -1.01
console.log( round(-2.175, 2) ); // -2.18
console.log( round(-5.015, 2) ); // -5.02``````

``````var value = Math.round(234.567*100)/100
``````

`````` var value = Math.round(234.567*10)/10
``````

``````angular.module('filters').filter('decimalPlace', function() {
return function(num, precision) {
var multiplier = Math.pow(10, precision || 0);
return Math.round(num * multiplier) / multiplier;
};
});
``````

``````{{model.value| decimalPlace}}
{{model.value| decimalPlace:1}}
{{model.value| decimalPlace: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
``````

``````function roundNumericStrings(str , numOfDecPlacesRequired){
var roundFactor = Math.pow(10, numOfDecPlacesRequired);
return (Math.round(parseFloat(str)*roundFactor)/roundFactor).toString();  }
``````

``````str.slice(0, -1)
``````

`Math.round( num * 10) / 10` 不起作用。

``````function badRound (num, precision) {
const x = 10 ** precision;
return Math.round(num * x) / x
}

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
``````
``````Math.round( mul/count * 10 ) / 10

Math.round(Math.sqrt(sqD/y) * 10 ) / 10
``````

``````function rnd(v,n=2) {
return Math.round((v+Number.EPSILON)*Math.pow(10,n))/Math.pow(10,n)
}
``````

``````roundWithMaxPrecision(11.234, 2); //11.23
roundWithMaxPrecision(11.234, 1); //11.2
roundWithMaxPrecision(11.234, 4); //11.23
roundWithMaxPrecision(11.234, -1); //10

roundWithMaxPrecision(4.2, 2); //4.2
roundWithMaxPrecision(4.88, 1); //4.9
``````

``````function roundWithMaxPrecision (n, precision) {
let precisionWithPow10 = Math.pow(10, precision);
return Math.round(n * precisionWithPow10) / precisionWithPow10;
}
``````