Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Decimal to String

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?

like image 383
gfrung4 Avatar asked Jun 19 '12 00:06

gfrung4


People also ask

How do you convert decimal to string?

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.

How do you cast a decimal number in Python?

If you are converting price (in string) to decimal price then.... from decimal import Decimal price = "14000,45" price_in_decimal = Decimal(price. replace(',','.

How do you do 2 decimal places in Python?

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.


2 Answers

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' 
like image 81
Gareth Latty Avatar answered Sep 21 '22 20:09

Gareth Latty


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'  
like image 27
Matthew Roberts Avatar answered Sep 17 '22 20:09

Matthew Roberts