如何限制双打印的小数位数?
这个程序有效,除非nJars的数量是7的倍数,我会得到一个答案,如$ 14.999999999999998。 对于6,输出为14.08。 如何修复7的倍数的exception,这样它会显示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); } }
使用DecimalFormatter :
double number = 0.9999999999999; DecimalFormat numberFormat = new DecimalFormat("#.00"); System.out.println(numberFormat.format(number));
会给你“0.99”。 您可以在右侧添加或减去0以获得更多或更少的小数。
或者使用右侧的“#”使附加数字可选,如#。##(0.30)会将尾随0降为(0.3)。
如果要在控制台上打印/写入double值,请使用System.out.printf()
或System.out.format()
方法。
System.out.printf("\n$%10.2f",shippingCost); System.out.printf("%n$%.2f",shippingCost);
查看DecimalFormat: http : //docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html
你会做的事情如下:
new DecimalFormat("$#.00").format(shippingCost);
或者,由于您正在使用货币,您可以看到NumberFormat.getCurrencyInstance()
如何为您工作。
使用DecimalFormat类来格式化double
您使用String.format()方法。
Formatter类也是一个不错的选择。 fmt.format(“%。2f”,变量); 2这里显示你想要多少小数。 例如,您可以将其更改为4。 不要忘记关闭格式化程序。
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; Formatter fmt = new Formatter(); fmt.format("%.2f", shippingCost); System.out.print("$" + fmt); fmt.close(); }
好吧,另外一个我认为只是为了它的乐趣的解决方案是将你的小数转换成一个字符串,然后将字符串切成2个字符串,一个包含点和小数,另一个包含在左边的Int点。 之后,将点和小数的字符串限制为3个字符,一个用于小数点,其他用于小数点。 然后重新组合。
double shippingCost = ((nCartons * 1.44) + (lbs + 1) * 0.96) + 3.0; String ShippingCost = (String) shippingCost; String decimalCost = ShippingCost.subString(indexOf('.'),ShippingCost.Length()); ShippingCost = ShippingCost.subString(0,indexOf('.')); ShippingCost = ShippingCost + decimalCost;
那里! 简单吧?