2

I need to find the way for converting the Float value in to the two point decimal.

I have a API code which is implemented already which will be returning the two Float value.

For example consider it is returning the values as follows: 293.019999504

But I need to make it as 293.01 instead of 293.019999504

As well as it should be handling 0 as 0.00

I am unable to modify the API implementation backend or DB tables.

I need to implement this in views.py where I am getting the values using the API calls.

Need a way to achieve this in pythonic way.

Sparky
  • 91
  • 1
  • 8

3 Answers3

3

You should do as follows:

a = 293.019999504
print("{0:.2f}".format(a))
>> 293.02
mvelay
  • 1,520
  • 1
  • 10
  • 23
0

IIUC you want to use the round function:

round(293.019999504,2)
Out[1]:
293.02

Note that it will round your number (so 293.019 will end up as 293.02), if you don't want that, you can use floor:

from math import floor
floor(100*293.019999504)/100
ysearka
  • 3,805
  • 5
  • 20
  • 41
0

If you really want to round down, you need something like

    int(293.019999504 * 100) / 100.0

However, the correct way of dealing with accounting matters is fixed point calculations as described here: https://docs.python.org/2/library/decimal.html.

Jorgen
  • 195
  • 1
  • 10