-4

I have the situation that I have floats (like 1.122, 1.3232, 1.22222) I and need to round it always in line with math rules to 2 decimal places: up if third is 5 or higher, down is third is lower than 5.

Like this (before round -> after round):

1.123 -> 1.12
1.1250 -> 1.13
1.0050 -> 1.01
1.0000 -> 1.00
1.00001 -> 1.00

(always two after ".")

Which way in Python is the best for this? I tried with round function, formatting, numpy, decimal and always sometimes it failed. Hint appreciated !

martineau
  • 119,623
  • 25
  • 170
  • 301
Pavel
  • 3
  • 2
  • Does this answer your question? [How to round numbers](https://stackoverflow.com/questions/27576691/how-to-round-numbers) – Maximilian Freitag Jan 11 '22 at 10:09
  • What do you mean sometimes it failed? Why does none of the functions you mentioned work for you? – D Malan Jan 11 '22 at 10:11
  • 1
    "I tried with round function, formatting, numpy, decimal and always sometimes it failed." How did it fail? When did it fail? – MisterMiyagi Jan 11 '22 at 10:11
  • A ``float`` has no concept of "decimal places". The numbers ``1.0000``, ``1.00`` and ``1.`` are exactly the same value. Are you trying to *format* the number, e.g. for printing or writing to a file? – MisterMiyagi Jan 11 '22 at 10:12
  • Unfortanelley not - I tried this ones – Pavel Jan 11 '22 at 10:12
  • 1
    I downvoted this question because OP refuses to clarify whether they want to round or format the numbers. – timgeb Jan 11 '22 at 10:21

1 Answers1

0

There is a function "round" that would be useful:

round(1.123, 2) -> 1.12

round(1.12345, 3) -> 1.123

UPDATE

If you want to get arithmetic rounding, you can use math package and your own function:

import math
def arithmetic_round(val):
    x = 0
    if (float(val) * 100 % 1) >= 0.5:
        x = math.ceil(val*100)/100
    else:
        x = math.floor(val*100)/100
    return format(x, '.2f')

But timgeb is right - 1.0050 is 1.004999 in Python terms.

That is why I would suggest to change 0.5 to 0.49:

import math
def arithmetic_round(val):
    x = 0
    if (float(val) * 100 % 1) >= 0.49:
        x = math.ceil(val*100)/100
    else:
        x = math.floor(val*100)/100
    return format(x, '.2f')


arithmetic_round(1.123) -> 1.12
arithmetic_round(1.1250) -> 1.13
arithmetic_round(1.0050) -> 1.01
arithmetic_round(1.0000) -> 1.00
arithmetic_round(1.00001) -> 1.00