Search code examples
pythonexcelfloating-pointdecimalfloating-accuracy

Truncating decimal digits like Excel in python


In my excel file, I've some calculations. Calculation returns 0,345 and excel convert it to 0,35. I made it in python. Python is returning 0,345, but I want to take 0,35 like Excel. I've tried with round() method, but it's returning 0.34.

calc = round(value * arg / 1000, 5)

Solution

  • Floating point numbers are inherently imprecise. Where n is the number of digits to round to, multiply by 10n, add 0.5, round, then divide by 10n.

    >>> number = 0.345
    >>> round(number * 10 ** 2 + 0.5) / 10 ** 2
    0.35