Skip to content

Instantly share code, notes, and snippets.

@richardwooding
Last active September 29, 2015 13:50
Show Gist options
  • Save richardwooding/ca7036ab0fb0806709d7 to your computer and use it in GitHub Desktop.
Save richardwooding/ca7036ab0fb0806709d7 to your computer and use it in GitHub Desktop.
Testing BigDecimal with Math.max versus BigDecimal.max
#!/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