Last active
September 29, 2015 13:50
-
-
Save richardwooding/ca7036ab0fb0806709d7 to your computer and use it in GitHub Desktop.
Testing BigDecimal with Math.max versus BigDecimal.max
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env groovy | |
// Math.min and Math.max are dangerous with BigDecimal due to loss of precision when converting to float | |
// We should be using BigDecimal.min and BigDecimal.max instead | |
// Proof | |
BigDecimal a = new BigDecimal('6270.30') | |
BigDecimal b = new BigDecimal('6270.30') | |
//Safe | |
BigDecimal c = a.max(b) | |
//Unsafe | |
BigDecimal d = Math.max(a,b) | |
println("A: ${a} B: ${b} C: ${c} D: ${d}") | |
// Output: | |
// A: 6270.30 B: 6270.30 C: 6270.30 D: 6270.3000000000001818989403545856475830078125 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment