Modulus is Versatile

Paul Brown @ 2006-01-30T17:10:00Z

I recently came across a post to a mailing list that asked how to truncate a Java double to two decimal place. The usual answers, either using a formatter and parser or multiplying by 100 and using floor() and then dividing by 100, will work, but there's an even simpler one:

double x = 12345.6789d;
double y = x - (x % 0.01);

As expected, y is 12345.67.

Meta

Tags: (tag) (tag)

(comment bubbles) 0 comments
299 direct views