如何限制双数打印的小数位数? [英] How do I limit the number of decimals printed for a double?

查看:122
本文介绍了如何限制双数打印的小数位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个程序可以工作,除了nJars的数量是7的倍数之外,我会得到一个答案,如$ 14.999999999999998。 6,输出为14.08。如何修复7的倍数的异常,这样会显示$ 14.99?

  import java.util.Scanner; 
public class Homework_17
{
private static int nJars,nCartons,totalOunces,OuncesTolbs,lbs;

public static void main(String [] args)
{
computeShippingCost();
}

public static void computeShippingCost()
{
System.out.print(输入一些jar:);
扫描仪kboard =新扫描仪(System.in);
nJars = kboard.nextInt();
int nCartons =(nJars + 11)/ 12;
int totalOunces =(nJars * 21)+(nCartons * 25);
int lbs = totalOunces / 16;
double shippingCost =((nCartons * 1.44)+(lbs + 1)* 0.96)+ 3.0;

System.out.print($+ shippingCost);
}
}


解决方案

使用 DecimalFormatter

  double number = 0.9999999999999; 
DecimalFormat numberFormat = new DecimalFormat(#。00);
System.out.println(numberFormat.format(number));

会给你0.99。您可以在右侧添加或减去0以获得更多或更少的小数。或者在右边使用'#',使额外的数字可以选择,如#。##(0.30)会将尾随0的值降至(0.3) 。


This program works, except when the number of nJars is a multiple of 7, I will get an answer like $14.999999999999998. For 6, the output is 14.08. How do I fix exceptions for multiples of 7 so it will display something like $14.99?

import java.util.Scanner;
public class Homework_17
{
 private static int nJars, nCartons, totalOunces, OuncesTolbs, lbs;

 public static void main(String[] args)
  {
   computeShippingCost();
  }

  public static void computeShippingCost()
  {
   System.out.print("Enter a number of jars: ");
   Scanner kboard = new Scanner (System.in);
   nJars = kboard.nextInt();
   int nCartons = (nJars + 11) / 12;
   int totalOunces = (nJars * 21) + (nCartons * 25);
   int lbs = totalOunces / 16;
   double shippingCost =  ((nCartons * 1.44) + (lbs + 1) * 0.96) + 3.0;

   System.out.print("$" + shippingCost);
   }
}

解决方案

Use a DecimalFormatter:

double number = 0.9999999999999;
DecimalFormat numberFormat = new DecimalFormat("#.00");
System.out.println(numberFormat.format(number));

Will give you "0.99". You can add or subtract 0 on the right side to get more or less decimals.

Or use '#' on the right to make the additional digits optional, as in with #.## (0.30) would drop the trailing 0 to become (0.3).

这篇关于如何限制双数打印的小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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