开发者

Problem with nontypical rounding in python

I'm testing a system wher开发者_如何转开发e 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


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.


[...] 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


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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜