Formatting a float number without trailing zeros

Question:

When I do a simple division in Python 3, such as 123000/1000, I get 123.0, or 4/2 I get 2.0. How do I get rid of the trailing zero in Python 3’s division?

EDIT:
I don’t want just simple integer division. For ex, 1234/1000 should give 1.234.
To be clear, this question is about formatting the output, not internal representation.

Asked By: ItM

||

Answers:

If you can guarantee that you get just a trailing zero, casting to int gets rid of it:

>>> 4/2
2.0
>>> int(4/2)
2
Answered By: Luciano
#  // => used for integer output
#   / => used for double output
x = 100/35      # => 2.857142857142857
y = 100//35     # => 2
z = 100.//35    # => 2.0    # floating-point result if divisor or dividend real
Answered By: Andrew St P

Mod is an O(1) operation which should add almost no overhead to your actual program. You could make it into a one liner also

x = a//b if not a % b else a/b

If you need to do this kind of thing a lot, make it into a function

def func(a, b):
    return a//b if not a % b else a/b
func(10, 2)      # out = 5
func(10, 3)      # out = 3.333333333
func(1200, 100)  # out = 12
func(1234, 1000) # out = 1.234
Answered By: SyntaxVoid

Thanks all for your help! The answer came from @vaultah:

>>> f'{2.1:g}'
'2.1'
>>> f'{2.0:g}'
'2'

So just use regular division such as 4/2 and then format the string.
From the docs for ‘g’: https://docs.python.org/2/library/string.html#format-specification-mini-language
“insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it.”

Answered By: ItM

You could use something like this:

def remove_trailing_zeros(x):
    return str(float(x)).rstrip('0').rstrip('.')

remove_trailing_zeros(1.23)  # '1.23'
remove_trailing_zeros(4.0)  # '4
remove_trailing_zeros(1000)  # '1000'

Normally, you would use standard string formatting options like '%2.1f' % number or any of the other many ways to format a string. However, you would then have to specify the amount of digits you want to display but in this case the number of trailing zeros to return is variable. The '%g' format specifier does not have this problem, but uses scientific notation and I don’t know if that is what the OP wants.

The above solution converts the number to a "nicely printable string representation" (str(x)), and then removes trailing zeros (.rstrip('0')) and if necessary the remaining trailing period (.rstrip('.')) (to avoid "1." as a result) using standard string methods.

Note: I added the cast to float to make sure the code works correctly for integers as well, in case anyone needs that.

Answered By: wovano

It’s “correct” behaviour to have “floats” as a result, and .0 part simply indicates this fact. I think that what matter to you is “representation” of the result in the string. So you should not change actual result and only change the way it’s “displayed”. Use formatting mini language:

>>> for val in (123000/1000, 4/2, 1234/1000): print(f"{val:g}")  # Use "General format" to represent floats
...                                                                                                                                                                                                                              
123                                                                                                                                                                                                                              
2                                                                                                                                                                                                                                
1.234

Answered By: imposeren

This works well for me. No scientific notation format for big numbers.

def no_trailing_zero(value: float) -> Union[float, int]:
    return int(value) if value % 1 == 0 else float(str(value))

>>> no_trailing_zero(50)
50
>>> no_trailing_zero(50.11)
50.11
>>> no_trailing_zero(50.1100)
50.11
>>> no_trailing_zero(50.0)
50
>>> no_trailing_zero(500000000.010)
500000000.01
>>>
Answered By: James H
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.