Round decimal – If 1 then no decimal, if 0.01 then 2 decimal

Question:

How can i truncate not with casual number like 1, 2, 3 but directly with decimal syntax?

For example:

  • I have 4 and decimal to 1 so truncate to 4.
  • I have 1.5 and decimal to 1 so truncate to 1.
  • I have 1.5689 and decimal 0.01 so truncate to 1.56.
  • I have 1.7954 and decimal 0.001 so truncate to 1.795.

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 …

Asked By: Valentin Garreau

||

Answers:

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.

Answered By: Vasilis G.

Can also do, using this and this:

import numpy as np
result = np.round(number, max(str(formattocopy)[::-1].find('.'),0))

Results, for number and formattocopy values:

number=1.234
formattocopy=1.2

Result: 1.2

number=1.234
formattocopy=1.234

Result: 1.234

Answered By: zabop

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
Answered By: wjandrea

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.

Answered By: Pranav Hosangadi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.