Skip to content

Commit

Permalink
make working setScale method on BigDecimal
Browse files Browse the repository at this point in the history
  • Loading branch information
bastie committed Dec 10, 2023
1 parent c758c48 commit ec465bd
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 45 deletions.
60 changes: 15 additions & 45 deletions Sources/JavApi/math/BigDecimal+Java.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,54 +13,24 @@ extension java.math.BigDecimal {
public static let ROUND_DOWN = 1

public func setScale (_ newScale : Int, _ roundingMode : Int) -> java.math.BigDecimal {
let before = self.exponent
var stringValue = ""
if before < 0 { // -2 = to chars after point
stringValue = "\(self)"

// trim to scale
var newStringValue = ""
var dotPosition = -1

for char in stringValue {
if char == "." { // found
dotPosition += 1
}
else {
if dotPosition < 0 { // before dot
newStringValue.append(char)
}
else {
if dotPosition * -1 > before { // in the scale
newStringValue.append(char)
}
dotPosition += 1 // next position after dot
}
}
// trimmed
stringValue = newStringValue
}

}
else { // FIXME: not real implemented
stringValue = "\((self as NSDecimalNumber).int64Value)"
}

let result = java.math.BigDecimal (string: stringValue)!

let roundMode : NSDecimalNumber.RoundingMode = switch (roundingMode) {
case 4 /* ROUND_HALF_UP */ : .plain
case 0 /* ROUND_UP */ : .up
case 1 /* ROUND_DOWN */ : .down
default : .bankers // FIXME: Java knows some more
var result = self
var doubleValue = (self as NSDecimalNumber).doubleValue
switch roundingMode {
case java.math.BigDecimal.ROUND_DOWN :
let string = String(format: "%.\(newScale)f" ,doubleValue)
result = java.math.BigDecimal.valueOf(string)!
case java.math.BigDecimal.ROUND_UP :
var factor = 10
for _ in 1..<newScale { factor *= 10 }
doubleValue = ceil(doubleValue * Double(factor)) / Double(factor)
let string = String(format: "%.\(newScale)f" ,doubleValue)
result = java.math.BigDecimal.valueOf(string)!
default:
fatalError("Please help! Not yet implemented round method.")
break;
}


_ = _BigDecimal.savedRoundMode [result, default: roundMode]
return result
}
}

internal class _BigDecimal {
internal static var savedRoundMode : [java.math.BigDecimal: NSDecimalNumber.RoundingMode] = [:]
}
9 changes: 9 additions & 0 deletions Tests/JavApiTests/JavApi_math_BigDecimal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,13 @@ final class JavApi_math_BigDecimal_Tests: XCTestCase {
XCTAssertEqual(VSP1, java.math.BigDecimal.valueOf("2325.00")!)

}

public func testScale2 () {
let pi = java.math.BigDecimal.valueOf(Double.pi)
let up = pi.setScale(2, java.math.BigDecimal.ROUND_UP)
let down = pi.setScale(2, java.math.BigDecimal.ROUND_DOWN)

XCTAssertEqual(up, 3.15)
XCTAssertEqual(down, 3.14)
}
}

0 comments on commit ec465bd

Please sign in to comment.