-3

I would like to convert the unicode string to float with 2 decimal places. I am using locale.atof() to covert to float. I know that we can use locale.format to format the resulting value to 2 decimal points. Is it possible to use a single function to convert from unicode to float with decimal precision specified ?

Currently i am using it like this

float(locale.format('%.2f',(locale.atof('3.145678'))) 

Is there any other way ?

SunilS
  • 2,030
  • 5
  • 34
  • 62
  • Where is your example? – user1767754 Jun 27 '17 at 11:23
  • locate.atof('3.145677777'). I need the output to be 3.14. Curently i am doing it this way. float(locale.format('%.2f',(locale.atof(i[3])*100)/snpdbtm)) – SunilS Jun 27 '17 at 11:24
  • A `float` doesn't have a specifiable number of decimal points. If your value is a string, you can choose the number of decimal points; if it's a float, you cannot. If anything you're asking how to trim a string containing a numeric value to a given number of decimal places; floats needn't enter the picture at all. – deceze Jun 27 '17 at 11:31

4 Answers4

1

You should consider the decimal module, which offers utils to deal with floating point precision, e.g.:

from decimal import Decimal as D
from decimal import ROUND_DOWN

d = D('3.145677777').quantize(D('0.01'))  
print(d)
# 3.15

You can set the rounding behaviour as well if you want to truncate:

d = D('3.145677777').quantize(D('0.01'), rounding=ROUND_DOWN)
print(d)
# 3.14
user2390182
  • 72,016
  • 6
  • 67
  • 89
1

The built-in round function rounds to the number of places specified, but there isn't one function that both converts a string and rounds.

>>> round(float('3.141592'),2)
3.14
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
0
float(("%.2f"%float('3.145')))
Sanket
  • 744
  • 7
  • 22
0

Define your own one function:

def trim_decimal_points(s):
    result = float(s)
    return format(result, '.2f')

Then use it as one function:

trim_decimal_points('3.145677777')
Nurjan
  • 5,889
  • 5
  • 34
  • 54