开发者

What should i have to change in that function to get the 0.00 like effect?

开发者 https://www.devze.com 2023-04-12 03:34 出处:网络
For to get the fraction point value upto two decim开发者_Python百科al Point i use this function.

For to get the fraction point value upto two decim开发者_Python百科al Point i use this function.

double roundTwoDecimals(double d) {             
    DecimalFormat twoDForm = new DecimalFormat("##.##");         
    return Double.valueOf(twoDForm.format(d)); 

But While there is a value like "5.50" then with this function i got only "5.5". Instead of that i want to get the 5.50 with the above function then what should i have to change ??

Please give me the Updated function or any suggestion to change the output like "0.00". Thanks.


Your example works fine for rounding numbers to 2 digits. But you will lose trailing zeros, because numeric variables (double, float, ...) do not store any formating information.

If you want to see trailing zeros (like 5.50) you have to format the numbers on output:

DecimalFormat twoDForm = new DecimalFormat("#0.00");         
System.out.println(twoDForm.format(d));


Use the format:

new DecimalFormat("#0.00")

When you use #, zero values display as absent. Using a 0 will ensure that either a digit or a 0 is displayed.


DecimalFormat.format returns a String (not a StringBuffer), which you are then getting the Double.valueOf(...). You then return the double value, which I assume when you print it uses it's own toString() to be displayed. You need to run the DecimalFormat.format on the double value returned.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号