public class Favorite {
public static void main(String[] arguments) {
String itemName = "Golden Beans";
double offerPrice = 314;
int sellPrice = 321;
double value = (sellPrice - offerPrice);
int cashStack = 500_000;
double percentageProfit = ((value / offerPrice) * 100);
System.out.println("Approx. Offer Price is " + offerPrice);
System.out.println("Approx. Sell Price is " + sellPrice);
System.out.println("The potential profit margin is " + value);
System.out.println("With a cash stack of " + cashStack + " we can buy " + cashStack / offerPrice + " " + itemName +"s");
System.out.println("The profit margin of " + itemName + " as a percentage is " + percentageProfit);
}
}
答案 0 :(得分:0)
尝试使用printf()
而不是println()
的格式,%.3f
:
System.out.printf("The profit margin of %s as a percentage is %.3f%n" itemName,percentageProfit);
答案 1 :(得分:0)
首先阅读文档-java docs:
System.out.printf("%.3f", res);
System.out.println(new java.text.DecimalFormat("#.000").format(500.12321313));
答案 2 :(得分:0)
您似乎正在寻找DecimalFormat https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
该类可以完成许多格式化数字的工作,从更改分隔符到按照所需方式自动舍入数字。
尝试实例化其中的一个,然后对其进行配置,并使用一些选项,直到您了解其工作原理为止,最后只需对要转换为String的任何数字调用其“ format”方法。