0

I know I can use format in order to format a number to whatever format. What I want is to format to at most n digts.

This can be achieved using the g-format-specifier. But there's one caveat here. What if my input is a really small number, e.g. -0.0000000001. With g this prints as -1e-10, but I want it to return simply 0.

I tried to do format(round(mynumber, 7)), but that interestingly gave me -0 (with a leading -) when mynumber is negative near zero.

How can I format mynumber to at most 7 digits without a leading sign, if the number is near zero?

Afterall this is my input and the expected result:

-0.0000000001 -> 0
 0.0000000001 -> 0
 3            -> 3
 3.1415927    -> 3.1415927
2
  • I got the output: 1e-07 when input is -0.0000000001. Is that Okay or not? Commented May 16 at 12:38
  • I used command abs() Commented May 16 at 13:02

3 Answers 3

1

or 0 is a short and quick way to replace negative zero:

for mynumber in -0.0000000001, 0.0000000001, 3, 3.1415927:
    print(round(mynumber, 7) or 0)

Attempt This Online!

Alternatively, also changing for example 3.0 to 3:

for mynumber in -0.0000000001, 0.0000000001, 3, 3.1415927, 3.0:
    x = round(mynumber, 7)
    if x.is_integer():
        x = int(x)
    print(x)

Attempt This Online!

Sign up to request clarification or add additional context in comments.

3 Comments

what about 3.0? With the above it prints as 3.0, while I want it to print 3.
@MakePeaceGreatAgain I don't see a really nice way, but I added a second approach that does it.
yeap, used that already but hoped for a more concise way. Thanks anyway.
0

One option is a quick function using abs() for 0.0 values like the one below.

def round_number(number, digits):
    rounded = round(number, digits)
    return abs(rounded) if rounded == 0.0 else rounded

print(round_number(-0.0000000001, 7))
 >> 0.0
print(round_number(0.0000000001, 7))
 >> 0.0
print(round_number(3, 7))
 >> 3
print(round_number(3.1415927, 7))
 >> 3.1415927

1 Comment

But I want 0, not 0.0. Anyway that seems really akward. Hoped for a more concise way.
-1

Just use a special case for if mynumber is -0 when rounded, like this:

if rounded == -0: rounded = 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.