Home > Mobile >  Format a decimal value to show 2 decimal places without using f-strings?
Format a decimal value to show 2 decimal places without using f-strings?

Time:10-11

num = 14.667789

I have the above value and i want output as output = 14.66 exact 2 places after the decimal without rounding off and without using f-strings and format in python. So is there any other way to get this?

CodePudding user response:

just an idea :

>>> bla=57.2654
>>> print(math.trunc(bla*100)/100)
57.26

CodePudding user response:

I assume that if you don't want to use f-strings or format (or %-formatting ?), which are pretty basics features of python, it may be due to a non-technical reason. Maybe it's some kind of test on your algorithm abilities.

If so, It's not the place for that.

I will point you the direction anyway. You may transform the number into a string, then use a loop to analyze every character of this string.

Good luck.

CodePudding user response:

You can use this instead:

from decimal import Decimal
num = 14.667789
output = float(Decimal(num).quantize(Decimal('1.00'),rounding="ROUND_DOWN"))
print(output)

Output:

14.66

  • Related