If the value is 200.3456, it should be formatted to 200.34.
If it is 200, then it should be 200.00.
If the value is 200.3456 , it should be formatted to 200.34 . If
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here’s an utility that rounds (instead of truncating) a double to specified number of decimal places.
For example:
Original version; watch out with this
This breaks down badly in corner cases with either a very high number of decimal places (e.g.
round(1000.0d, 17)) or large integer part (e.g.round(90080070060.1d, 9)). Thanks to Sloin for pointing this out.I’ve been using the above to round “not-too-big” doubles to 2 or 3 decimal places happily for years (for example to clean up time in seconds for logging purposes: 27.987654321987 -> 27.99). But I guess it’s best to avoid it, since more reliable ways are readily available, with cleaner code too.
So, use this instead
(Adapted from this answer by Louis Wasserman and this one by Sean Owen.)
Note that
HALF_UPis the rounding mode “commonly taught at school”. Peruse the RoundingMode documentation, if you suspect you need something else such as Bankers’ Rounding.Of course, if you prefer, you can inline the above into a one-liner:
new BigDecimal(value).setScale(places, RoundingMode.HALF_UP).doubleValue()And in every case
Always remember that floating point representations using
floatanddoubleare inexact.For example, consider these expressions:
For exactness, you want to use BigDecimal. And while at it, use the constructor that takes a String, never the one taking double. For instance, try executing this:
Some excellent further reading on the topic:
floatanddoubleif exact answers are required” in Effective Java (2nd ed) by Joshua BlochIf you wanted String formatting instead of (or in addition to) strictly rounding numbers, see the other answers.
Specifically, note that
round(200, 0)returns200.0. If you want to output “200.00“, you should first round and then format the result for output (which is perfectly explained in Jesper’s answer).