Decimal precision correct?

I need to apply .bankers rounding mode but I’m getting some unexpected results when instiating some Decimals, I’m just wondering if this is a bug, expected behavior or what am I missing.


import Foundation

extension Decimal {
   func rounded(_ scale: Int, _ roundingMode: RoundingMode = .bankers) -> Decimal {
        var toRound = self
        var rounded = Decimal()
        NSDecimalRound(&rounded, &toRound, scale, roundingMode)
        return rounded

var a: Decimal = NSDecimalNumber(floatLiteral: 6.422).decimalValue
print(a.rounded(1, .bankers))//6.4

var b: Decimal = NSDecimalNumber(floatLiteral: 6.4872).decimalValue
print(b.rounded(2, .bankers))//6.49

var c: Decimal = NSDecimalNumber(floatLiteral: 6.997).decimalValue
print(c.rounded(2, .bankers))//7

var d: Decimal = NSDecimalNumber(floatLiteral: 6.6500).decimalValue
print(d.rounded(1, .bankers))//6.6

var e: Decimal = NSDecimalNumber(floatLiteral: 7.485).decimalValue//wrong?
var e2: Decimal = Decimal(floatLiteral: 7.485)//wrong?
print(e.rounded(2, .bankers))//7.49 wrong?, it should be 7.48
print(e2.rounded(2, .bankers))//7.49 wrong?, it should be 7.48

var f: Decimal = NSDecimalNumber(floatLiteral: 6.755000).decimalValue
print(f.rounded(2, .bankers))//6.76

var g: Decimal = NSDecimalNumber(floatLiteral: 8.995).decimalValue//wrong?
var g2: Decimal = Decimal(floatLiteral: 8.995)//wrong?
print(g.rounded(2, .bankers))//8.99 wrong?, it should be 9.00
print(g2.rounded(2, .bankers))//8.99 wrong?, it should be 9.00

var h: Decimal = NSDecimalNumber(floatLiteral:  6.6501).decimalValue
print(h.rounded(1, .bankers))//6.7

var i: Decimal = NSDecimalNumber(floatLiteral:  7.4852007).decimalValue
print(i.rounded(2, .bankers))//7.49

var j: Decimal = NSDecimalNumber(floatLiteral:  19.57).decimalValue
print(j.rounded(2, .bankers))//19.57


Thank you in advance!

Powered by WPeMatico


You may also like...

Comments are closed.