parseDecimal in JavaScript?

20,669

Yes. Always, ALWAYS deal in units of the smallest denomination, and ONLY divide by 100 at the end, for display purposes only.

Share:
20,669
jeffery_the_wind
Author by

jeffery_the_wind

Currently a Doctoral student in the Dept. of Math and Stats at Université de Montréal. In the past I have done a lot of full stack development and applied math. Now trying to focus more on the pure math side of things and theory. Always get a lot of help from the Stack Exchange Community! Math interests include optimization and Algebra although in practice I do a lot of machine learning.

Updated on June 12, 2020

Comments

  • jeffery_the_wind
    jeffery_the_wind almost 4 years

    I have some JS calculations going on. Since floating point arithmetic often uses close approximations to numbers instead of exact values, if you round these floating point number to fixed precision, you often get slight differences. When you are dealing with dollars, people don't like these slight differences.

    My problem is outlined in this jsfiddle: http://jsfiddle.net/rGP8Q/.

    Does anyone know how I can do math operations (multiplication and addition) without introducing these rounding errors coming from the floating point approximations?

    EDIT

    I found this other post which brings up the same problem, and confirms that JS does not have a built in decimal data type: How to deal with floating point number precision in JavaScript?.

    you can see if you JS terminal that

    626.175.toFixed(2) == 626.17
    626.185.toFixed(2) == 626.18
    626.195.toFixed(2) == 626.20
    

    which is inconsistent. We need a true decimal data type.