如何在Java中舍入双值
我尝试将双精度值舍入为2精度值。我使用日期格式获得它,但它是字符串。 如何在不使用日期格式的情况下将双精度值舍入到精度 下面是一个例子如何在Java中舍入双值,java,Java,我尝试将双精度值舍入为2精度值。我使用日期格式获得它,但它是字符串。 如何在不使用日期格式的情况下将双精度值舍入到精度 下面是一个例子 public class RoundValue { public static void main(String[] args) { double kilobytes = 1205.6358; System.out.println("kilobytes : " + kilobytes); double new
public class RoundValue
{
public static void main(String[] args)
{
double kilobytes = 1205.6358;
System.out.println("kilobytes : " + kilobytes);
double newKB = Math.round(kilobytes*100.0)/100.0;
System.out.println("kilobytes (Math.round) : " + newKB);
DecimalFormat df = new DecimalFormat("###.##");
System.out.println("kilobytes (DecimalFormat) : " + df.format(kilobytes));
}
}
输出:
kilobytes : 1205.6358
kilobytes (Math.round) : 1205.64
kilobytes (DecimalFormat) : 1205.64
正如EJP和Leonidos在评论中所说,适当的四舍五入是通过类执行的,而不是通过
double
仔细选择你的。是打破关系(甚至分裂)的常见方式,但最好的方式取决于你的目的和情况
double d = 7.345;
java.math.BigDecimal bigDecimal = new java.math.BigDecimal(d).setScale(2, java.math.RoundingMode.HALF_EVEN);
System.out.println("My big decimal is: " + bigDecimal ); // Outputs: 7.34 (using Banker's Rounding)
请参阅:请提供您的问题代码…您是希望将打印值(用于显示目的)或变量本身(用于计算目的)四舍五入以共享您的场景plz,您是否希望类似的内容?也许BigDecimal是您的选择?双打不太适合真正的四舍五入。不四舍五入,所以没有答案,技术也不好。