1

how I should avoid decimal rounding in javascript suppose I have input like

input : 99999999999.999999 
Expected output : 99999999999.999999 

but i am getting output like

 100000000000

here, internally javascript rounding the decimal place. please let me know how should I avoid this javascript rounding???.

For example:

var test = 99999999999.999999;
console.log(test); //This will print 100000000000 instead
John Skoumbourdis
  • 3,041
  • 28
  • 34
Shivkumar
  • 1,903
  • 5
  • 21
  • 32

2 Answers2

3

As @Aliendroid suggested, you can use the BigDecimal.js library. In my perspective, this is the best way to handle double and floats in JavaScript

To answer to your question more specifically, you can actually do this:

var test_number = new BigDecimal('99999999999.999999'); 
console.log(test_number.setScale(6).toString());

and to your original question:

please let me know how should I avoid this javascript rounding???

Well you can't as there is not double number in JavaScript, only float. So for example if you do something like this:

console.log(99999999999.99); //This is a float number

This will actually output: 99999999999.99

John Skoumbourdis
  • 3,041
  • 28
  • 34
1

It is NOT Rounding

It is floating point error

learn floating point number in programming !

use string if needed and some Big number library

Ref:

http://floating-point-gui.de/

https://github.com/dtrebbien/BigDecimal.js

Aliendroid
  • 515
  • 3
  • 9
  • Link only answers are not welcomed in stackoverflow as they may become dead links. consider adding more info to your answer – Arash Milani Jul 10 '14 at 09:19
  • Arash, agree with you! But this is not a link only answer. This is an answer and it has some references. So +1 for @Aliendroid from me :) – John Skoumbourdis Jul 10 '14 at 09:27
  • @JohnSkoumbourdis Sorry john I don't see the websites linked look like a reference. Are they something like MDN as a reference for JavaScript? – Arash Milani Jul 10 '14 at 09:41
  • Just to clarify, I am not saying that it is the best answer. Of course solutions with code will be much better. I am just saying that it is not a bad answer. – John Skoumbourdis Jul 10 '14 at 10:11