Reputation: 17
I would like to be able to limit the amount of decimal places that are shown from a print function without any sort of rounding system
v = 8.836333333333339
print ('%.2f' % v)
This code will print the value of v to two decimal places but also rounds it up or down, how could I make it stop this rounding please?
Upvotes: 0
Views: 232
Reputation: 11
<?php
$value_exp = explode(".", 245.788968);
$value_new = floatval($value_exp[0].'.'.substr($value_exp[1],0,4));
echo $value_new; //output will 245.7889
?>
Upvotes: -1
Reputation: 12316
A bit specific to your case, but you could also use int
to truncate:
>>> print(int(v*100)/100.0)
8.83
It times at about 3x faster (310 ns vs 925 ns) than the string find
-based approach.
Upvotes: 0
Reputation: 4128
If you know how long the number will be, you can easily accomplish this with string slicing.
>>> v = 8.836333333333339
>>> x = str(v) # get string representation of 'v'
>>> x
'8.836333333333339'
>>> y = x[0:4] # every character in 'x' between 0 and 4 but not including 4
>>> y
'8.83'
>>> v = float(y) # you can even convert it back to a number if you want
>>> v
8.83
Upvotes: 1
Reputation: 15501
You could process it as a string:
v = 8.836333333333339
s = str(v)
print s[:s.find('.')+3]
# prints 8.83
Upvotes: 1
Reputation: 16940
How about using decimal module :
>>> help(Decimal.quantize)
Help on method quantize in module decimal:
quantize(self, exp, rounding=None, context=None, watchexp=True) unbound decimal.Decimal
method
Quantize self so its exponent is the same as that of exp.
Similar to self._rescale(exp._exp) but with error checking.
>>> from decimal import *
>>> v = 8.834333333333339
>>> print Decimal(v).quantize(Decimal('0.01'))
8.83
>>> print Decimal('8.8663').quantize(Decimal('0.01'))
8.87
>>> print Decimal('8.863').quantize(Decimal('0.01'))
8.86
>>>
Upvotes: 0