[英]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.