-4
x = 0.2
y= 12
z= x/y #0.0166666666667

On using round(z,2) i get 0.02 , where i need the system to take only 0.01.

Usr_Dev
  • 77
  • 1
  • 1
  • 9
  • 1
    What behavior are you looking for, in general? Do you want to always round down? Or maybe round towards 0 for negative numbers? – Amy Teegarden Jul 16 '15 at 20:10
  • Well its rounding up because that's normal behavior. If you want a smaller decimal you can do round(z,2) but that will still return 0.02. – Snhp9 Jul 16 '15 at 20:11
  • I am expecting the value to be 0.01, which function to be used? – Usr_Dev Jul 16 '15 at 20:14
  • 1
    But *why* are you expecting the value to be 0.01? What is your logic? For example: "3+5 = 8, but I expect 10 *because I want to round up to the nearest 10*". – showdev Jul 16 '15 at 20:54
  • @showdev *Ours is not to wonder why...* – Adam Smith Jul 16 '15 at 21:00

4 Answers4

2

The only way I can think of would be multiplying by 100, using the math.floor() function, then dividing by 100. I don't like it at all, though.

z = (math.floor(100*(x/y)))/100
Jeremy
  • 818
  • 6
  • 19
2

If you'd like to avoid casting to str and slicing, you can cast to Decimal and use quantize

from decimal import Decimal, ROUND_DOWN

x = 0.2
y = 12
z = Decimal(x/y).quantize(Decimal('1.00'), rounding=ROUND_DOWN)
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
1

Although I think I know what you wanna do, that logic is not right in mathematics. In math you either round up or down-- which is why python gave you 0.02.

My guess is you just want the whole number part and a number of decimal places after. Try this then:

def cut_down(number, dec_plc):// needs a decimal and number of decimal places.

z_str= str(number)  
z_str= z_str[:dec_plc+3] places
return float(z_str)
BattleDrum
  • 798
  • 7
  • 13
0

if you want to show only 0.01 out of 0.016666667, you can use

>>> str(z)[0:4]
>>> '0.01'

How to get a substring from a string

dot.Py
  • 5,007
  • 5
  • 31
  • 52