lon*_*kie 35 java floating-point android
可能重复:
如何在Java中将数字舍入到n个小数位
我很难将浮点数舍入到小数点后两位.我已经尝试了一些我在这里看到的方法,包括只是使用Math.round()
,但无论我做什么,我都会得到不寻常的数字.
我有一个我正在处理的浮动列表,列表中的第一个显示为1.2975118E7
.什么是E7
?
当我使用Math.round(f)
(f是浮动)时,我得到完全相同的数字.
我知道我做错了什么,我只是不确定是什么.
我只想要数字格式x.xx
.第一个数字应该是1.30
,等等.
Ale*_*der 102
1.2975118E7
是科学记数法.
1.2975118E7 = 1.2975118 * 10^7 = 12975118
Run Code Online (Sandbox Code Playgroud)
此外,Math.round(f)
返回一个整数.您无法使用它来获得所需的格式x.xx
.
你可以用String.format
.
String s = String.format("%.2f", 1.2975118);
// 1.30
Run Code Online (Sandbox Code Playgroud)
kco*_*ock 50
如果您正在寻找货币格式(您没有指定,但似乎这是您正在寻找的)尝试NumberFormat
该类.这很简单:
double d = 2.3d;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String output = formatter.format(d);
Run Code Online (Sandbox Code Playgroud)
哪个将输出(取决于区域设置):
$2.30
此外,如果不需要货币(只是精确的两位小数),您可以使用此代码:
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String output = formatter.format(d);
Run Code Online (Sandbox Code Playgroud)
哪个会输出 2.30
您可以利用它DecimalFormat
来为您提供您想要的风格.
DecimalFormat df = new DecimalFormat("0.00E0");
double number = 1.2975118E7;
System.out.println(df.format(number)); // prints 1.30E7
Run Code Online (Sandbox Code Playgroud)
由于它采用科学记数法,因此在不损失那么多数量级精度的情况下,您将无法获得小于10 7的数字.
归档时间: |
|
查看次数: |
107187 次 |
最近记录: |