四舍五入使用Math.rint()如何确定小数位数

tongliquan 2007-05-17 09:34:39
比如下面这个小程序的结果为2,我想得到2.4该怎么改呢.请给出改后的程序.
public class Ma
{
public static void main(String args[])
{
double k,i;
i=2.3+0.06;;
k=Math.rint(i);
System.out.println("结果为:"+i);
}
}
...全文
554 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
吴恒 2007-05-17
  • 打赏
  • 举报
回复
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
string s = formatter.format(3.236)
daniel_kaka 2007-05-17
  • 打赏
  • 举报
回复
控制位数的四舍五入你可以使用DecimalFormat:

double d = 12345.56784;
DecimalFormat ddf = new DecimalFormat("#0.00");//保留两位小数
System.out.println(ddf.format(d));
daniel_kaka 2007-05-17
  • 打赏
  • 举报
回复
public static double rint(double a)返回其值最接近参数并且是整数的 double 值。如果两个整数的 double 值都同样接近,那么结果取偶数。特殊情况是:
如果参数值是整数,那么结果就是该参数。
如果参数是 NaN 或无穷大或正零或负零,那么结果与参数相同。

参数:
a - double 值。
返回:
最接近 a 的整数浮点值

-------------------------

lz用错了吧~
harold2007 2007-05-17
  • 打赏
  • 举报
回复
sf
kunling123 2007-05-17
  • 打赏
  • 举报
回复
import java.text.DecimalFormat;

public class DD {

public static void main(String args[])
{
double k,i;
k=2.36;
DecimalFormat df=new DecimalFormat("#.#");

System.out.println("结果为:"+df.format(k));
}
}
zhaohuiji 2007-05-17
  • 打赏
  • 举报
回复
import java.text.DecimalFormat;

public class Ma
{
public static void main(String args[])
{
DecimalFormat df= new DecimalFormat("#0.0");

double k,i;
i=2.3+0.06;;

System.out.println(df.format(i));
}
}
//你试试!
  • 打赏
  • 举报
回复
new BigDecimal(i).setScale(1, BigDecimal.ROUND_HALF_UP)..doubleValue();
==============================
这个比较准确,否则会出现只返回偶数位的情况,不信试试NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
string s = formatter.format(3.225)

此时得到的是3.22而不是四舍五入想得到的3.23
malligator 2007-05-17
  • 打赏
  • 举报
回复
k=Math.rint(i);

->

k=new BigDecimal(i).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
malligator 2007-05-17
  • 打赏
  • 举报
回复
new BigDecimal(i).setScale(1, BigDecimal.ROUND_HALF_UP)..doubleValue();

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧