我需要在Java中将float浮点到两位小数 [英] I need to round a float to two decimal places in Java

查看:157
本文介绍了我需要在Java中将float浮点到两位小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


我有困难四舍五入到小数点后两位。我已经尝试了一些我在这里看到的方法,包括简单地使用 Math.round(),但是不管我做什么,我都会得到不寻常的数字。



我有一个正在处理的浮动列表,列表中的第一个显示为 1.2975118E7 。什么是 E7



当我使用 Math.round(f) code>(f是浮点数),我得到完全相同的数字。

我知道我做错了什么,我只是不知道是什么。 / p>

我只是希望这些数字的格式是 x.xx 。第一个数字应该是 1.30 等等。

解决方案

1.2975118E7 科学记数法

  1.2975118E7 = 1.2975118 * 10 ^ 7 = 12975118 

另外, Math.round(f)返回一个整数。你不能用它来得到你想要的格式 x.xx



你可以使用 String.format

 字符串s = String.format(%。2f,1.2975118); 
// 1.30


Possible Duplicate:
How to round a number to n decimal places in Java

I am having difficulties rounding a float to two decimal places. I have tried a few methods I have seen on here including simply just using Math.round(), but no matter what I do I keep getting unusual numbers.

I have a list of floats that I am processing, the first in the list is displayed as 1.2975118E7. What is the E7?

When I use Math.round(f) (f is the float), I get the exact same number.

I know I am doing something wrong, I just am not sure what.

I just want the numbers to be in the format x.xx. The first number should be 1.30, etc.

解决方案

1.2975118E7 is scientific notation.

1.2975118E7 = 1.2975118 * 10^7 = 12975118

Also, Math.round(f) returns an integer. You can't use it to get your desired format x.xx.

You could use String.format.

String s = String.format("%.2f", 1.2975118);
// 1.30

这篇关于我需要在Java中将float浮点到两位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆