Search code examples
javascriptnode.jsfloating-pointnumbers

Java Script parseFloat() unexpected decimal places


Why when I am cast this string "2019275.159999999916180968" to number, or when used parseFloat(str). I'm always get result "2019275.16". Why it remove extra decimal places that provided in the string? And how can i keep number of decimal places, without rounding it to 2 decimal places in this case?

Amount of decimal places in the string is dynamical.


Solution

  • It might be worth investigating a library like decimal.js to help with this. e.g.:

    Decimal.set({ precision: 24 }); // The default of 20 is not big enough for the number below so you may need to adjust this
    
    let a = new Decimal('2019275.159999999912345');
    a = a.plus(1);
    
    let b = new Decimal('2019275.159999999912345').plus(1);
    let c = Decimal.add('2019275.159999999912345', 1);
    
    console.log(a, b, c);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/9.0.0/decimal.min.js"></script>