Can I do it with System.out.print
?
相关问题
- 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
Output is 22.35. If you need 3 decimal points change it to "%.3f".
I would suggest using String.format() if you need the value as a
String
in your code.For example, you can use
String.format()
in the following way:You can use the
printf
method, like so:In short, the
%.2f
syntax tells Java to return your variable (val
) with 2 decimal places (.2
) in decimal representation of a floating-point number (f
) from the start of the format specifier (%
).There are other conversion characters you can use besides
f
:d
: decimal integero
: octal integere
: floating-point in scientific notationJust do
String str = System.out.printf("%.2f", val).replace(",", ".");
if you want to ensure that independently of the Locale of the user, you will always get / display a "." as decimal separator. This is a must if you don't want to make your program crash if you later do some kind of conversion likefloat f = Float.parseFloat(str);
A simple trick is to generate a shorter version of your variable by multiplying it with e.g.
100
, rounding it and dividing it by100.0
again. This way you generate a variable, with 2 decimal places:This "cheap trick" was always good enough for me, and works in any language (I am not a Java person, just learning it).