How to display an output of float data with 2 deci

2019-01-01 09:02发布

Can I do it with System.out.print?

13条回答
琉璃瓶的回忆
2楼-- · 2019-01-01 09:30
float f = 102.236569f; 
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f)); // output is 102.24
查看更多
浮光初槿花落
3楼-- · 2019-01-01 09:30
float floatValue=22.34555f;
System.out.print(String.format("%.2f", floatValue));

Output is 22.35. If you need 3 decimal points change it to "%.3f".

查看更多
看风景的人
4楼-- · 2019-01-01 09:31

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:

float myFloat = 2.001f;

String formattedString = String.format("%.02f", myFloat);
查看更多
孤独寂梦人
5楼-- · 2019-01-01 09:32

You can use the printf method, like so:

System.out.printf("%.2f", val);

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 integer
  • o: octal integer
  • e: floating-point in scientific notation
查看更多
时光乱了年华
6楼-- · 2019-01-01 09:33

Just 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 like float f = Float.parseFloat(str);

查看更多
墨雨无痕
7楼-- · 2019-01-01 09:34

A simple trick is to generate a shorter version of your variable by multiplying it with e.g. 100, rounding it and dividing it by 100.0 again. This way you generate a variable, with 2 decimal places:

double new_variable = Math.round(old_variable*100) / 100.0;

This "cheap trick" was always good enough for me, and works in any language (I am not a Java person, just learning it).

查看更多
登录 后发表回答