Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change 39.54484700000000 to 39.54 and using python [duplicate]

Possible Duplicate:
python limiting floats to two decimal points

i want to set 39.54484700000000 to 39.54 using python ,

how to get it ,

thanks

like image 879
zjm1126 Avatar asked Mar 05 '11 06:03

zjm1126


People also ask

What does %s mean in Python?

%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string. It automatically provides type conversion from value to string.

How do you convert a float to two decimal places in Python?

Use str. format() with “{:. 2f}” as string and float as a number to display 2 decimal places in Python.

What is the meaning of %D in Python?

The %d operator is used as a placeholder to specify integer values, decimals or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified. Floating-point numbers are converted automatically to decimal values.


3 Answers

If you want to change the actual value, use round as Eli suggested. However for many values and certain versions of Python this will not result be represented as the string "39.54". If you want to just round it to produce a string to display to the user, you can do

>>> print "%.2f" % (39.54484700000000)
39.54

or in newer versions of Python

>>> print("{:.2f}".format(39.54484700000000))
39.54

or with the fstrings

>>> print(f'{39.54484700000000:.2f}')
39.54

Relevant Documentation: String Formatting Operations, Built-in Functions: round

like image 57
Jeremy Avatar answered Oct 22 '22 13:10

Jeremy


How about round

>>> import decimal
>>> d=decimal.Decimal("39.54484700000000")
>>> round(d,2)
39.54
like image 3
the wolf Avatar answered Oct 22 '22 13:10

the wolf


You can use the quantize method if you're using a Decimal:

In [24]: q = Decimal('0.00')

In [25]: d = Decimal("115.79341800000000")

In [26]: d.quantize(q)
Out[26]: Decimal("115.79")
like image 3
ars Avatar answered Oct 22 '22 13:10

ars