There are tons of topics on here that explain how to convert a string to a decimal, but how do I convert a decimal back to a string?
Like if I did this:
import decimal dec = decimal.Decimal('10.0')
How would I take dec
and get '10.0'
(a string) out?
To convert a Decimal value to its string representation using a specified culture and a specific format string, call the Decimal. ToString(String, IFormatProvider) method.
If you are converting price (in string) to decimal price then.... from decimal import Decimal price = "14000,45" price_in_decimal = Decimal(price. replace(',','.
In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.
Use the str()
builtin, which:
Returns a string containing a nicely printable representation of an object.
E.g:
>>> import decimal >>> dec = decimal.Decimal('10.0') >>> str(dec) '10.0'
Use the string format function:
>>> from decimal import Decimal >>> d = Decimal("0.0000000000000123123") >>> s = '{0:f}'.format(d) >>> print(s) 0.0000000000000123123
If you just type cast the number to a string it won't work for exponents:
>>> str(d) '1.23123E-14'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With