小数后只显示两位数字

如何得到小数点后两位数的双精度值。

比如说

如果

i=348842.
double i2=i/60000;
tv.setText(String.valueOf(i2));

生成 5.81403333的代码。

但我只要 5.81

那我该怎么办?

421937 次浏览

Use DecimalFormat.

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.

Code snippet -

double i2=i/60000;
tv.setText(new DecimalFormat("##.##").format(i2));

Output -

5.81

i=348842.
double i2=i/60000;
DecimalFormat dtime = new DecimalFormat("#.##");
i2= Double.valueOf(dtime.format(time));
v.setText(String.valueOf(i2));

How about String.format("%.2f", i2)?

First thing that should pop in a developer head while formatting a number into char sequence should be care of such details like do it will be possible to reverse the operation.

And other aspect is providing proper result. So you want to truncate the number or round it.

So before you start you should ask your self, am i interested on the value or not.

To achieve your goal you have multiple options but most of them refer to Format and Formatter, but i just suggest to look in this answer.

I think the best and simplest solution is (KISS):

double i = 348842;
double i2 = i/60000;
float k = (float) Math.round(i2 * 100) / 100;

Here i will demonstrate you that how to make your decimal number short. Here i am going to make it short upto 4 value after decimal.

  double value = 12.3457652133
value =Double.parseDouble(new DecimalFormat("##.####").format(value));

Many other answers only do formatting. This approach will return value instead of only print format.

double number1 = 10.123456;
double number2 = (int)(Math.round(number1 * 100))/100.0;
System.out.println(number2);