Heri H Rachmat
Heri H Rachmat

Reputation: 13

Javascript Round function

a                formula       b
31,283,700,000   round(a,-6)   31,284,000,000
60,204,605       round(a,-4)   60,200,000

I have an formula to process the currency value, but I have difficulties to achieve the same result by using , any ideas to solve this?

Thanks.

Upvotes: 1

Views: 145

Answers (3)

mseifert
mseifert

Reputation: 5670

Here is a javascript rounding function which fixes javascript floating point rounding errors as well as takes care of what you were asking for. A more complete description can be found in this post.

Javascript floating point errors can occur as described by this post:

Binary floating point math is like this. In most programming languages, it is based on the IEEE 754 standard. JavaScript uses 64-bit floating point representation, which is the same as Java's double. The crux of the problem is that numbers are represented in this format as a whole number times a power of two; rational numbers (such as 0.1, which is 1/10) whose denominator is not a power of two cannot be exactly represented.

function round(number, precision) {
  number = +number;
  precision = precision ? +precision : 0;
  if (precision == 0) {
    return Math.round(number);
  }
  var sign = 1;
  if (number < 0) {
    sign = -1;
    number = Math.abs(number);
  }

  // Shift
  number = number.toString().split('e');
  number = Math.round(+(number[0] + 'e' + (number[1] ? (+number[1] + precision) : precision)));
  // Shift back
  number = number.toString().split('e');
  return +(number[0] + 'e' + (number[1] ? (+number[1] - precision) : -precision)) * sign;
}

console.log(round(31283700000, -6)) //31,284,000,000
console.log(round(60204605, -4)) //60,200,000

Upvotes: 1

Parker Ziegler
Parker Ziegler

Reputation: 1010

If you're alright with using a library, lodash has a method for this, _.round(number, [precision=0]) - computes number rounded to precision.

console.log(_.round(31283700000, -6));
console.log(_.round(60204605, -4));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Upvotes: 1

Amadan
Amadan

Reputation: 198324

Rounding is easy to implement:

function excelRound(n, e) {
  let f = Math.pow(10, e);
  return Math.round(n * f) / f;
}

console.log(31283700000, -6, excelRound(31283700000, -6));
console.log(60204605, -4, excelRound(60204605, -4));

Upvotes: 3

Related Questions