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.
            Asked
            
        
        
            Active
            
        
            Viewed 322 times
        
    0
            
            
        - 
                    1I found this to be helpful https://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators – Kenneth Githambo Apr 07 '21 at 14:03
- 
                    @KennethGithambo, that's for the thousandths separator. OP wants a comma instead of a dot to separate the decimal part. – Apr 07 '21 at 14:07
- 
                    https://stackoverflow.com/questions/7106417/convert-decimal-mark – Apr 07 '21 at 14:10
4 Answers
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
        
- 2,091
- 2
- 6
- 24
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)
 
    
    
        Hemza RAHMANI
        
- 11
- 2
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
        
- 457
- 3
- 10
- 
                    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]. – ChrisGPT was on strike 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
        
- 426
- 1
- 4
- 16
