admin管理员组文章数量:1327962
I have a bunch of numbers, for example 797.3333333333334
, 852.22222111
, 933.111023
, which I want to ALWAYS round up to the nearest penny, such that the numbers I already mentioned would be 797.34
, 852.23
, 933.12
, respectively.
I said the nearest penny, but you might also call it the nearest tenth.
There is a ceiling function, but that only rounds to the nearest integer, as does Math.round()
I have a bunch of numbers, for example 797.3333333333334
, 852.22222111
, 933.111023
, which I want to ALWAYS round up to the nearest penny, such that the numbers I already mentioned would be 797.34
, 852.23
, 933.12
, respectively.
I said the nearest penny, but you might also call it the nearest tenth.
There is a ceiling function, but that only rounds to the nearest integer, as does Math.round()
-
ceil
doesn't round to nearest integer, it gets the first integer larger or equal to your number. – XCS Commented Nov 22, 2014 at 22:28
3 Answers
Reset to default 8The Math.ceil(x) function returns the smallest integer greater than or equal to a number "x".
var rounded = Math.ceil(yourNumber * 100)/100;
Just do it like this: Math.ceil(number * 100) / 100
.
Properly rounding to the nearest penny:
var yourNumber = 5.495;
yourNumber = Math.round(yourNumber * 100)/100;
alert(yourNumber);
Always round up to the nearest penny:
function precision(a) {
if (!isFinite(a)) return 0;
var e = 1, p = 0;
while (Math.round(a * e) / e !== a) {
e *= 10; p++;
}
return p;
}
if (precision(yourNumber) >= 3) {
yourNumber = (Math.trunc(yourNumber * 100)/100) * 1 + 0.01;
}
本文标签: How to always round a number UP to the nearest penny in JavascriptStack Overflow
版权声明:本文标题:How to always round a number UP to the nearest penny in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742251211a2440795.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论