0

I want to round numbers so that two numbers are used after the last zero, or decimal if the number is greater than 1. I've looked up the documentation for round, but can't seem to find this feature.

If I use round, it always round to n decimals places regardless.

This is the output I'm looking for:

42.0068 --> 42.01
0.00251 --> 0.0025
420.246 --> 420.25
0.192 -> 0.19
0.00000000128 --> 0.0000000013
kingkong.js
  • 659
  • 4
  • 14

2 Answers2

1

The kind of rounding you're asking for isn't a common operation.

In terms of common operations you have two cases (ignoring sign since all your examples are positive):

  1. If the value is less than 1, round to significant figures (eg per the link in @quamrana's comment on the question).
  2. Else (ie the value is at least 1), round to decimal places in the usual way.

Your final code would reasonably be a function with a simple if-else:

def round_special(value):
  if value < 1:
    return round_to_sf(value, 2)
  else:
    return round_to_dp(value, 2)
Scruffy
  • 580
  • 8
  • 23
0

You could try with string manipulation. It's not that elegant, but seems to work. It's up to you to complete this code to handle exceptions..

if number>1:
    result = round(number,2)
else:
    str_number = str(number)
    i = str_number.rfind('0')
    result = float(str_number[:i+3])
 
rok
  • 2,574
  • 3
  • 23
  • 44