Skip to content

Instantly share code, notes, and snippets.

@mcquinne
Created April 30, 2012 18:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcquinne/2560562 to your computer and use it in GitHub Desktop.
Save mcquinne/2560562 to your computer and use it in GitHub Desktop.
Round a number to a multiple of another number, optionally altering the rounding technique used.
import static java.math.RoundingMode.*
import java.math.RoundingMode
/*
To round to a multiple:
1) normalize the input by dividing it by the multiple value.
2) round it to the nearest integer using the desired rounding technique
3) multiply that integer by the multiple value to produce the result
NOTES:
CEILING and FLOOR modes round up and down in value, while UP and DOWN
modes round on absolute value. e.g. the FLOOR of -1.2 is -2, while -1.2 rounded
DOWN is -1.
Groovy will automatically cast any Number to a BigDecimal as it's
passed into these functions.
There's no error checking here, e.g. this will blow up if the multiple is zero.
Maybe it's okay to let the math libraries throw exceptions for us though, since
there's not really any more graceful way to handle that.
*/
BigDecimal roundUp( BigDecimal num, BigDecimal multiple ) {
round( num, multiple, CEILING )
}
BigDecimal roundDown( BigDecimal num, BigDecimal multiple ) {
round( num, multiple, FLOOR )
}
BigDecimal round( BigDecimal num, BigDecimal multiple, RoundingMode mode = HALF_UP ) {
return (num / multiple).setScale( 0, mode ) * multiple
}
assert roundUp( 1.2, 0.5 ) == 1.5
assert roundUp( 1.4, 0.5 ) == 1.5
assert roundUp( -1.2, 0.5 ) == -1
assert roundUp( -1.4, 0.5 ) == -1
assert roundDown( 1.2, 0.5 ) == 1
assert roundDown( 1.4, 0.5 ) == 1
assert roundDown( -1.2, 0.5 ) == -1.5
assert roundDown( -1.4, 0.5 ) == -1.5
assert roundUp( 1.2, 2 ) == 2
assert roundUp( 1.4, 2 ) == 2
assert roundUp( -1.2, 2 ) == 0
assert roundUp( -1.4, 2 ) == 0
assert roundDown( 1.2, 2 ) == 0
assert roundDown( 1.4, 2 ) == 0
assert roundDown( -1.2, 2 ) == -2
assert roundDown( -1.4, 2 ) == -2
assert roundUp( (float) 1.2, 0.5 ) == 1.5
assert roundUp( (double) 1.2, 0.5 ) == 1.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment