[英]Java DecimalFormat - Using Integers
我有一个美分的货币,作为整数(例如: 1234
)。 我需要的输出是: $12.34
。 我们不允许在此赋值中使用双精度或浮点数,只能使用整数。
这是我所拥有的:
totalChange = 1234;
DecimalFormat ourFormat = new DecimalFormat("$#,###.00");
String totalString = ourFormat.format(totalChange);
System.out.println("Your change of " + totalString + " is as follows:");
我假设DecimalFormat从右到左,将34
分配到小数点之后,而12
应该放在前面。
我得到Your change of $1234.00 is as follows:
的输出Your change of $1234.00 is as follows:
格式不会人为地引入输入中不存在的小数位。
您可以先尝试转换为美元和美分,然后将两者与'。
int dollars = totalChange / 100;
int cents = totalChange % 100;
提示 (基于@DanielFischer的评论)
分可以是1位或2位数字,但您可能希望始终将其输出为2位数字。
这个问题可能正试图教您有关整数除法和模数的知识。
除以整数时,余数将被完全舍弃,因此,如果需要该信息,则需要使用模运算符。 模运算符(%)仅给您除法的余数。 例如5/3 = 1和5%3 = 2。
这些操作非常适合您的问题。
假设我想算出我需要多少镍和几美分才能进行准确的更改。
int totalChange = 27; //I have 27¢
int nickels = totalChange / 5; //This gives 5 and discards the remainder
int pennies = totalChange % 5; //This gives 2, the remainder from your previous division
要进行格式化,请使用Formatter.format(),将美元和美分作为参数,并使用前导$对其进行格式化,并精确地将2位数字作为美分(如上述人士所建议)。 由于这是家庭作业,因此我不会放弃如何做到这一点,但是javadocs应该可以帮助您:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax
我不知道这是否违反您的规定(听起来确实很奇怪,但是很麻烦)。 你可以试试
int totalChange = 1234;
DecimalFormat ourFormat = new DecimalFormat("$#,###.00");
String totalString = ourFormat.format(totalChange / 100f);
System.out.println("Your change of " + totalString + " is as follows:");
否则,我认为您需要提供自己的格式化程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.