Skip to content

Commit

Permalink
BugFix BigDecimal.setScale with less than 1
Browse files Browse the repository at this point in the history
  • Loading branch information
bastie committed Dec 11, 2023
1 parent ee602d8 commit 396d450
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ Check out these projects and learn how to use JavApi⁴Swift.

* [ASCII-Data](https://github.com/bastie/ASCII-Data2JavApi.git) is a library to display tables and graphs on command line as ASCII or ANSI.

### 0.7.3
### 0.7.4

* [LStXML2Code](https://github.com/bastie/LStXML2Code) is a library and CLI to generate source code for German income tax calculation based on Federal Ministry of Finance provided XML Pseudocode.

Expand Down
17 changes: 15 additions & 2 deletions Sources/JavApi/math/BigDecimal+Java.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,21 @@ extension java.math.BigDecimal {
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)!
var down = ""
if newScale > 0 {
down = String(format: "%.\(newScale)f" ,doubleValue)
}
else if newScale == 0 {
down = String(format:"%\(newScale)d",Int(doubleValue))
}
else {
let plusScale = newScale * -1
var computedFactor = 10
for _ in 1..<plusScale { computedFactor *= 10 }
doubleValue = Double( (Int(doubleValue) / computedFactor) * computedFactor )
down = String(format: "%\(newScale)f" ,doubleValue)
}
result = java.math.BigDecimal.valueOf(down)!
case java.math.BigDecimal.ROUND_UP :
let factor = switch newScale {
case 0 : {return Double(1)}
Expand Down
12 changes: 12 additions & 0 deletions Tests/JavApiTests/JavApi_math_BigDecimal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,17 @@ final class JavApi_math_BigDecimal_Tests: XCTestCase {

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

// scale 0 second test
let toRoundWithZero = java.math.BigDecimal (1103802.8199999998);
let roundOne = toRoundWithZero.setScale (1, java.math.BigDecimal.ROUND_DOWN);
let roundZero = toRoundWithZero.setScale (0, java.math.BigDecimal.ROUND_DOWN);
let roundMinusOne = toRoundWithZero.setScale (-1, java.math.BigDecimal.ROUND_DOWN);

XCTAssertEqual(roundOne, java.math.BigDecimal.valueOf("1103802.8")!)
XCTAssertEqual(roundZero, java.math.BigDecimal.valueOf("1103802")!)
XCTAssertEqual(roundMinusOne, java.math.BigDecimal.valueOf("1.10380E+6")!)


}
}

0 comments on commit 396d450

Please sign in to comment.