我希望最多保留两位小数,但只有必要时才这样做。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
我该如何在JavaScript中实现这个?
我希望最多保留两位小数,但只有必要时才这样做。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
我该如何在JavaScript中实现这个?
一个精确的四舍五入方法。来源:Mozilla
(function(){
/**
* Decimal adjustment of a number.
*
* @param {String} type The type of adjustment.
* @param {Number} value The number.
* @param {Integer} exp The exponent (the 10 logarithm of the adjustment base).
* @returns {Number} The adjusted value.
*/
function decimalAdjust(type, value, exp) {
// If the exp is undefined or zero...
if (typeof exp === 'undefined' || +exp === 0) {
return Math[type](value);
}
value = +value;
exp = +exp;
// If the value is not a number or the exp is not an integer...
if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
return NaN;
}
// Shift
value = value.toString().split('e');
value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
// Shift back
value = value.toString().split('e');
return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
}
// Decimal round
if (!Math.round10) {
Math.round10 = function(value, exp) {
return decimalAdjust('round', value, exp);
};
}
// Decimal floor
if (!Math.floor10) {
Math.floor10 = function(value, exp) {
return decimalAdjust('floor', value, exp);
};
}
// Decimal ceil
if (!Math.ceil10) {
Math.ceil10 = function(value, exp) {
return decimalAdjust('ceil', value, exp);
};
}
})();
例子:
// Round
Math.round10(55.55, -1); // 55.6
Math.round10(55.549, -1); // 55.5
Math.round10(55, 1); // 60
Math.round10(54.9, 1); // 50
Math.round10(-55.55, -1); // -55.5
Math.round10(-55.551, -1); // -55.6
Math.round10(-55, 1); // -50
Math.round10(-55.1, 1); // -60
Math.round10(1.005, -2); // 1.01 -- compare this with Math.round(1.005*100)/100 above
// Floor
Math.floor10(55.59, -1); // 55.5
Math.floor10(59, 1); // 50
Math.floor10(-55.51, -1); // -55.6
Math.floor10(-51, 1); // -60
// Ceil
Math.ceil10(55.51, -1); // 55.6
Math.ceil10(51, 1); // 60
Math.ceil10(-55.59, -1); // -55.5
Math.ceil10(-59, 1); // -50
这可能会帮助您:
var result = Math.round(input*100)/100;
欲了解更多信息,您可以查看Math.round(num) vs num.toFixed(0) and browser inconsistencies
使用这个函数Number(x).toFixed(2);
Number
中:Number(Number(x).toFixed(2));
。 - user993683Number
的调用是不必要的,x.toFixed(2)
就可以了。 - bgusach(1).toFixed(2)
返回的是 1.00
,但是在这种情况下提问者需要的是 1
。 - Eugene Mala1.005.toFixed(2)
得到的结果是"1"
,但它应该是"1.01"
。 - Adam Jagosz对我来说,Math.round() 没有给出正确��答案。我发现使用 toFixed(2) 更好。 以下是两者的示例:
console.log(Math.round(43000 / 80000) * 100); // wrong answer
console.log(((43000 / 80000) * 100).toFixed(2)); // correct answer
+(10).toFixed(2); // = 10
+(10.12345).toFixed(2); // = 10.12
(10).toFixed(2); // = 10.00
(10.12345).toFixed(2); // = 10.12
试用这个轻巧的解决方案:
function round(x, digits){
return parseFloat(x.toFixed(digits))
}
round(1.222, 2);
// 1.22
round(1.222, 10);
// 1.222
return Number(x.toFixed(digits))
之间有什么区别吗? - user993683.toFixed()
只允许使用数字。 - petermeissnerround(1.005,2)
并查看结果为1
而不是1.01
。 - MilConDoinround(0.995, 2) => 0.99
; round(1.006, 2) => 1.01
; round(1.005, 2) => 1
- petermeissner有几种方法可以做到这一点。对于像我这样的人,Lodash的变体
function round(number, precision) {
var pair = (number + 'e').split('e')
var value = Math.round(pair[0] + 'e' + (+pair[1] + precision))
pair = (value + 'e').split('e')
return +(pair[0] + 'e' + (+pair[1] - precision))
}
用法:
round(0.015, 2) // 0.02
round(1.005, 2) // 1.01
如果您的项目使用jQuery或Lodash,您还可以在这些库中找到适当的round
方法。
Number.toFixed()
会返回一个带加号的字符串,但是JS解释器会将该字符串转换为数字。这是一种语法糖。 - stanleyxu2005alert((+1234).toFixed(2))
会显示"1234.00"。 - Marcos Limaalert(+1234.toFixed(2))
会抛出SyntaxError: identifier starts immediately after numeric literal
的错误。我选择第一种选项。 - Marcos Lima362.42499999999995
(jsfiddle)。期望结果(如PHP中的echo round(362.42499999999995, 2)
):362.43
。实际结果:362.42
。 - Dr. Gianluigi Zane Zanettini362.42
还是362.43
?我在PHP中进行了一些测试,我认为这是PHP浮点数精度问题。如果您运行echo(362.42499999999995);
,您将获得362.425
,并且PHP使用此数字进行2位小数的四舍五入,它返回362.43
。我认为这是一个PHP问题,而不是数学问题。 - stanleyxu20052017年
只需使用原生代码.toFixed()
number = 1.2345;
number.toFixed(2) // "1.23"
如果您需要严格控制并仅在必要时添加数字,可以使用 replace
函数。
number = 1; // "1"
number.toFixed(5).replace(/\.?0*$/g,'');
toFixed
,而且它不符合问题中"必要时才执行"的条件;(1).toFixed(2)
的结果为"1.00"
,而问题提出者希望得到"1"
。 - Mark Amery
const formattedNumber = new Intl.NumberFormat('en', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(myNumber); const formattedNumberInNumber = parseFloat(formattedNumber);``` // #=> 1.28。[更多信息](https://dev59.com/anI-5IYBdhLWcg3wsKl4#1726662)
- tinystone