简体   繁体   中英

Convert float to string with dynamic precision - python

I want to convert float value (with dynamic precision) to string if float value which i am getting a = 10.00 than result should be '10.00' and if a = 10.000 than result should be '10.000'

I am getting result like this

a = 10.00
str(a)
'10.0'

But I want result like this.

a = 10.00
str(a)
'10.00'

Is there any way ?

If you're trying to preserve significant digits, then use the decimal module.

>>> from decimal import Decimal
>>> num1 = Decimal('10.000')
>>> str(num1)
'10.000'
>>> num2 = Decimal('10.00')
>>> str(num2)
'10.00'

The decimal module does support decimal floating point arithmetic.

>>> num1/5
Decimal('2.000')
>>> num1+22
Decimal('32.000')

i am getting a = 10.00 than result should be '10.00' and if a = 10.000 than result should be '10.000'

if 'a = 5.500 than str(a) should be '5.500' if 'a = 10.50 than str(a) should be '10.50' if 'a = 1.050 than str(a) should be '1.050'

What you are asking for is not possible. Not in Python, and not in any other programming language that I know of. If a is a regular floating point number, then 10.0 is the same as 10.00 or 10.000 . They are all stored the same and have the same precision.

>>> a = 5.500
>>> b = 5.5
>>> c = 5.500000000
>>> a == b == c
True

The only way to circumvent this, is not to use float , but another type, like Decimal , as suggested in another answer.

Let me explain one scenario where I am allowing user to enter input from command line, say for example user enter 10.00, I want both 0's after decimal, currently amount becomes 10.0

According to your last comment, you get the numbers from a text input, ie as str , so it should be no problem to use decimal . But if you just want to echo those numbers back to the user, you don't need even that: Just print the string the user originally entered.

note that I am accepting only numbers from user input(I do not want to allow string input

You can just get string input and convert that input to a number. Problem solved.

>>> s = raw_input("enter number ")
enter number 10.000
>>> f = float(s)
>>> s
'10.000'
>>> f
10.0
# way 1
a = 10.00
s = '%.2f' % a
print s # 10.00

# way 2
a = 10.0
p = 2
s = '%.{0}f'.format(p) % a
print s # 10.00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM