Skip to content

Commit

Permalink
add special case round down with zero
Browse files Browse the repository at this point in the history
  • Loading branch information
bastie committed Dec 10, 2023
1 parent ec465bd commit e899d8d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
13 changes: 10 additions & 3 deletions Sources/JavApi/math/BigDecimal+Java.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,16 @@ extension java.math.BigDecimal {
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 factor = switch newScale {
case 0 : {return Double(1)}
case 1 : {return Double(10)}
default : {
var computedFactor = 10
for _ in 1..<newScale { computedFactor *= 10 }
return Double(computedFactor)
}
}
doubleValue = ceil(doubleValue * factor()) / factor()
let string = String(format: "%.\(newScale)f" ,doubleValue)
result = java.math.BigDecimal.valueOf(string)!
default:
Expand Down
12 changes: 9 additions & 3 deletions Tests/JavApiTests/JavApi_math_BigDecimal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,20 @@ final class JavApi_math_BigDecimal_Tests: XCTestCase {
VSP1 = (VSP1.multiply(RVSATZAN)).setScale(2,java.math.BigDecimal.ROUND_DOWN)
XCTAssertEqual(VSP1, java.math.BigDecimal.valueOf("2325.00")!)

}

public func testScale2 () {
// simple round of PI
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)

// scale 0 test

let downZero = pi.setScale(0, java.math.BigDecimal.ROUND_DOWN)
let upZero = pi.setScale(0, java.math.BigDecimal.ROUND_UP)

XCTAssertEqual(downZero, 3)
XCTAssertEqual(upZero, 4)
}
}

0 comments on commit e899d8d

Please sign in to comment.