Skip to content
Advertisement

How to copy R’s print(x, digits = n) in Python?

In R print(x, digits=n) does something a little complicated.

It always shows all the digits to the left of the decimal point and then, if there are any digits to the right it rounds the whole number so that at most n digits are shown.

Examples:

print(2,digits=2)
2
print(23,digits=2)
23
print(23.12,digits=2)
23
print(2.12,digits=2)
2.1
print(0.126,digits=2)
0.13
print(23236.12,digits=6)
23236.1
print(123,digits=2)
123

How would you do that in Python?

You can try these examples online at https://rdrr.io/snippets/

Advertisement

Answer

Here is an actual solution to the problem, although it requires some string operations, it should work

def my_round(value, digits):
    non_dec = str(value).split('.')[0]
    non_dec_len = len(non_dec) if non_dec != '0' else 0
    return round(value, digits - non_dec_len if digits > non_dec_len else None)
    
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement