0

I have float 12.200000 and I need to use string formatting to output 12,20. How do I do that? I am total begginer and I can't figure it out from the docs.

Andrew
  • 995
  • 7
  • 14

4 Answers4

1

This is how I did it:

flt = 12.200000
flt = str(flt)

if len(flt) == 4:
    flt += "0"
print(flt.replace(".", ","))

What this does, is first turn the float into a string. Then, we check if the length of the string is 4. If it is 4, we add a zero at the end. Finally, at the end, we replace the . into a ,. This gives the desired output of 12,20.

The Pilot Dude
  • 1,672
  • 1
  • 3
  • 19
1

If your value is a float than you can simply cast it to string and use the replace() method.

value = 12.200000
output = str(value).replace(".", ",")
print(output)
1

Use round to ge the float to first two decimal places. To replace the . with a , you need to convert the float to a string and use flt.replace('.',',') to get the desired answer. Convert it back to a float data type.

flt = 12.200000
flt = round(flt,2)
flt = str(flt) 
flt.replace('.',',') # Replace . with ,
float(flt)  # 12,20
Shorya Sharma
  • 349
  • 2
  • 8
  • Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please [edit] your question and explain how it answers the specific question being asked. See [answer]. – Chris Apr 08 '21 at 01:12
0
float = str(float)
#this converts the float to a string

float = float.replace(".", ",")
#this replaces the point with a comma

if len(float) == 4:
  float += "0"
#this checks whether the float should end with a zero, and if it does it adds it
LWB
  • 95
  • 5