简体   繁体   中英

How to always round a number UP to the nearest penny in Javascript

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

就是这样: 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM