This question already has an answer here:
If the value is 200.3456
, it should be formatted to 200.34
.
If it is 200
, then it should be 200.00
.
This question already has an answer here:
If the value is 200.3456
, it should be formatted to 200.34
.
If it is 200
, then it should be 200.00
.
For two rounding digits. Very simple and you are basically updating the variable instead of just display purposes which DecimalFormat does.
x = Math.floor(x * 100) / 100;
If you just want to print a
double
with two digits after the decimal point, use something like this:If you want to have the result in a
String
instead of being printed to the console, useString.format()
with the same arguments:Or use class
DecimalFormat
:In your question, it seems that you want to avoid rounding the numbers as well? I think .format() will round the numbers using half-up, afaik?
so if you want to round, 200.3456 should be 200.35 for a precision of 2. but in your case, if you just want the first 2 and then discard the rest?
You could multiply it by 100 and then cast to an int (or taking the floor of the number), before dividing by 100 again.
You might have issues with really really big numbers close to the boundary though. In which case converting to a string and substring'ing it would work just as easily.
If you really want the same double, but rounded in the way you want you can use BigDecimal, for example
Rounding a double is usually not what one wants. Instead, use
String.format()
to represent it in the desired format.