Reputation: 1063
How can i truncate not with casual number like 1, 2, 3 but directly with decimal syntax?
For example:
I don't know if such a function exist, but i imagine something like this:
round(1.5689, 0.01)
-> 1.56
I don't even know how we can call that lol ...
Upvotes: 0
Views: 459
Reputation: 7846
One possible approach to solve the above would be to find out how many decimals are after the decimal separator .
. Then, if you know the number of those decimals, you can easily round your input number. Below is an example:
def truncate(number, decimal):
decPart = str(decimal).split('.')
p = len(decPart[1]) if len(decPart) > 1 else 1
return round(number, p) if p > 1 else int(number)
print(truncate(4,1))
print(truncate(1.5,1))
print(truncate(1.5689,0.01))
print(truncate(1.7954,0.001))
Output:
4
1
1.57
1.795
I noticed that your round function floors the number. If this is the case, you can simply parse your number as string, round it to the number of decimals you want and then convert it back to number.
Upvotes: 3
Reputation: 25489
Let's use maths instead of programming!
We know that round(x, n)
rounds x
to n
decimal places. What you want is to pass 10**n
to your new function instead of n
. So,
def round_new(x, n):
return round(x, int(-math.log10(n))
This should give you what you want without the need for any string search / split operations.
Upvotes: 0
Reputation: 32954
This is a great application for the decimal
module, especially decimal.Decimal.quantize
:
import decimal
pairs = [
('4', '1'),
('1.5', '1'),
('1.5689', '0.01'),
('1.7954', '0.001')
]
for n, d in pairs:
n, d = map(decimal.Decimal, (n, d)) # Convert strings to decimal number type
result = n.quantize(d, decimal.ROUND_DOWN) # Adjust length of mantissa
print(result)
Output:
4
1
1.56
1.795
Upvotes: 2