显示小数点后只有两位数小数点、两位数

2023-09-12 22:31:49 作者:薄情薄意少年冷心冷意

如何让double值后,只有两位小数。

How to get the double value that is only two digit after decimal point.

例如

如果

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

这code发电 5.81403333

不过,我想只有 5.81

那么768,16怎么办?

So what shoud I do?

推荐答案

使用 DecimalFormat的。

的DecimalFormat是NumberFormat的一个具体子类,格式化   十进制数。它具有多种功​​能,旨在使   可以在任何语言环境来分析和格式化数字,包括支持   西,阿拉伯语,印度语和数字。它还支持不同   种的数,包括整数(123),定点数   (123.4),科学记数法(1.23E4),百分数(12%)和货币   数额($ 123)。所有这些可以本地化。

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段的 -

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

输出的 -

5.81