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()

Share Improve this question edited Feb 24, 2015 at 21:32 maudulus asked Nov 22, 2014 at 22:26 maudulusmaudulus 11.1k11 gold badges85 silver badges121 bronze badges 1
  • 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
Add a ment  | 

3 Answers 3

Reset to default 8

The 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