-1

Goal

I want to convert all floats to two decimal places regardless of number of decimal places float has without repeating convert code.

For example, I want to convert

50 to 50.00

50.5 to 50.50

without repeating the convert code again and again. What I mean is explained in the following section - research.

Not what this question is about

This question is NOT about:

  1. Only limiting floats to two decimal points - if there is less than two decimal points then I want it to have two decimal points with zeros for the unused spaces.

  2. Flooring the decimal or ceiling it.

  3. Rounding the decimal off.

This question is not a duplicate of this question.

That question only answers the first part of my question - convert floats to two decimal places regardless of number of decimal places float has, not the second part - without repeating convert code.

Nor this question.

That is just how to add units before the decimal place. My question is: how to convert all floats to two decimal places regardless of number of decimal places float has without repeating convert code.

Research

I found two ways I can achieve the convert. One is using the decimal module:

from decimal import *
TWOPLACES = Decimal(10) ** -2
print(Decimal('9.9').quantize(TWOPLACES))

Another, without using any other modules:

print(f"{9.9:.2f}")

However, that does not fully answer my question. Realise that the code to convert keeps being needed to repeat itself? I keep having to repeat the code to convert again and again. Sadly, my whole program is already almost completed and it will be quite a waste of time to add this code here and there so the format will be correct. Is there any way to convert all floats to two decimal places regardless of number of decimal places float has without repeating convert code?

Clarification

What I mean by convert is, something like what Dmytro Chasovskyi said, that I want all places with floats in my program without extra changes to start to operate like decimals. For example, if I had the operation 1.2345 + 2.7 + 3 + 56.1223183 it should be 1.23 + 2.70 + 3.00 + 56.12.

Also, float is a number, not a function.

  • have you looked at https://stackoverflow.com/questions/1424638/pad-python-floats – Anand Sowmithiran Dec 15 '21 at 13:37
  • What do you mean by convert? Do you want all places with floats in your program without extra changes to start to operate like decimals? So for example, you had operation 1.2345 + 2.7 + 3 + 56.1223183 and they should be 1.23 + 2.70 + 3.00 + 56.12? – Dmytro Chasovskyi Dec 15 '21 at 13:40
  • Also, the question is how do you use float? Is it a `float` function or just a number 2.5678? – Dmytro Chasovskyi Dec 15 '21 at 13:41
  • @DmytroChasovskyi Yes, that is exactly my goal. –  Dec 15 '21 at 13:42
  • @DmytroChasovskyi Just a number –  Dec 15 '21 at 13:43
  • 1
    If you wish to spend a little time you create a subclass of float which does all your converting, this may have been a nice implemetation early in your project which I'm not sure that you are willing to implement now. – Albin Sidås Dec 15 '21 at 13:43
  • @AlbinSidås I'm definitely willing to implement it now. It is better than adding the code for every line I use the float number. –  Dec 15 '21 at 13:45
  • I think @AlbinSidås is correct. You can also change your print function to a different function that formats float numbers as you would like them. Instead of print(f"{9.9:.2f}") you would have output(9.9) and inside there you can do the formatting. Then just do a search and replace for "print" with "output" – Cary H Dec 15 '21 at 13:49
  • maybe you should just use `Decimal` instead of floats everywhere? – Anentropic Dec 15 '21 at 13:59

3 Answers3

1

The bad news is: there is no "float" with "two decimal places".

Floating point numbers are represented internally with a fixed number of digits in base 2. https://floating-point-gui.de/basic/ .

And these are both efficient and accurate enough for almost all calculations we perform with any modern program.

What we normally want is that the human-readable text representation of a number, in all outputs of a program, shows only two digits. And this is controlled at wherever your program is either writting the value to a text file, to the screen, or rendering it to an HTML template (which is "writing it to a text file", again).

So, it happens that the same syntaxes that will convert a number to text, embedded in another string, allows additionally to control the exact output of the number. You put as an example print(f"{9.9:.2f}"). The only thing that looks impractical there is due to you hardcoding your number along with its conversion. Typically, the number will be in a variable.

Them, all you have to do is writting, wherever you output the number:

print(f"The value is: {myvar:.02f}")

instead of

print(f"The value is: {myvar}")

Or in whatever function you are calling that will need the rendered version of the number instead of print. Notice that the use of the word "rendered" here is deliberate: while your program is running, the number is stored in an efficient way in memory, directly usable by the CPU, that is not human readable. At any point you want to "see" the number, you have to convert it into text. It is just that some calls to it implicitly, like print(myvar). Then, just resort to explicitly converting it in these places - `print(f"{myvar:.02f}").

really having 2 decimal places in memory

If you use decimal.Decimal, then yes, there are ways to keep the internal representation of the number with 2 decimal digits, but them, instead of just converting the number on output, you must convert it into a "2 decimal place" value on all inputs as well

That means that whenever ingesting a number into your program, be it typed by the user, read from a binary file or database, or received via wire from a sensor, you have to apply a similar transform to the one used in the output as detailed above. More precisely: you convert your float to a properly formatted string, and then convert that to a decimal.Decimal.

And this will prevent your program of accumulating errors due to base conversion, but you will still need to force the format to 2 decimal places on every output, just like above.

jsbueno
  • 99,910
  • 10
  • 151
  • 209
0

Use this function.

def cvt_decimal(input):
    number = float(input)
    return ("%.2f" % number)

print(cvt_decimal(50))
print(cvt_decimal(50.5))

Output is :

50.00
50.50


** Process exited - Return Code: 0 **
Press Enter to exit terminal
Ali Amini Bagh
  • 39
  • 1
  • 2
  • 14
0

you can modify the decimal precision, even if you do any operation between 2 decimal types

import decimal
from decimal import Decimal

decimal.getcontext().prec = 2

a = Decimal('0.12345')
b = Decimal('0.12345')

print(a + b)

enter image description here

Decimal calculations are precise but it takes more time to do calculations, keep that in mind.