2

I'm testing a system where is specific rounding - last number is always rounded up

e.g.

  • 123,459 should yield 123,46
  • 99,9911 should yield 100,00

How can I implement it in python?

EDIT

The most important thing - those numbers are prices

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
user278618
  • 19,306
  • 42
  • 126
  • 196
  • in your seconds example the last digit isn't rounded up. You basically just reducing the precision to 2 digits, which is something entirely different. Also, are you using , as the decimal point? (I know some countries use that) if so please change it to . because most SO users will find it confusing. – Assaf Lavie Jun 17 '11 at 07:58
  • Which is the "last number", and why shouldn't the second example be `99,991`? – aioobe Jun 17 '11 at 07:58
  • Are you using `decimal`? If not why not? – David Heffernan Jun 17 '11 at 08:06

3 Answers3

4
import math
def myRounding(x):
   return math.ceil(x*100) / 100.0

Note that due to floating point not being able to express all decimal fractions, some results won't be able to be expressed in floating point numbers. If this is an issue, calculate in fixed-point numbers (i.e. 1.23 is represented by 123, with a fixed factor of 0.01), or use decimal.Decimal.

phihag
  • 278,196
  • 72
  • 453
  • 469
0

[...] last number is always rounded up.

This rounds to n-1 decimals where n represents the number of digits after the decimal point.

def roundupLast(x):
    return round(x, len(str(x).split(".")[-1]) - 1)


print(roundupLast(123.459))  # 123.46
print(roundupLast(99.9911))  # 99.991
print(roundupLast(99.9916))  # 99.992
aioobe
  • 413,195
  • 112
  • 811
  • 826
-1

You can do it using formatter

NSNumber *Numero = 99.99
NSNumberFormatter *Formatter = [[NSNumberFormatter alloc] init] ;
[Formatter setNumberStyle:NSNumberFormatterDecimalStyle];     

//Formatter ROUNDING MODE
[Formatter setRoundingMode:NSNumberFormatterRoundUp];

[Formatter setMinimumFractionDigits:2];
[Formatter setMaximumFractionDigits:2];

result = [Formatter stringFromNumber:Numero];
[Formatter release];
axel22
  • 32,045
  • 9
  • 125
  • 137
Tommaso
  • 155
  • 2
  • 10