I'm having some problems formatting the decimals of a double. If I have a double value, e.g. 4.0, how do I format the decimals so that it's 4.00 instead?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Works 100%.
An alternative method is use the
setMinimumFractionDigits
method from theNumberFormat
class.Here you basically specify how many numbers you want to appear after the decimal point.
So an input of
4.0
would produce4.00
, assuming your specified amount was 2.But, if your
Double
input contains more than the amount specified, it will take the minimum amount specified, then add one more digit rounded up/downFor example,
4.15465454
with a minimum amount of 2 specified will produce4.155
Try it online
Use String.format:
String.format("%.2f", 4.52135);
First import
NumberFormat
. Then add this:This will give you two decimal places and put a dollar sign if it's dealing with currency.