954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Question on Decimal

Hi,
I want my output to show to two decimals.If the output is $6.075,instead of bring it to $6.08,i prefer it showed $6.07.How am i able to do this?
I used the below System.Out but kept getting $6.08.

System.out.printf("%s%.2f\n","State Withholding(9.0%):$",stateWithholding);


Thank You :)

Valiantangel
Junior Poster in Training
62 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

Do you just want to display the result rounded down to 2 dec places, or do you need to perform the calculation and round down that result to2 dec places before doing anything else (eg storing or printing it)

JamesCherrill
Posting Genius
Moderator
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 
Do you just want to display the result rounded down to 2 dec places, or do you need to perform the calculation and round down that result to2 dec places before doing anything else (eg storing or printing it)

Prefer the latter.stateWithholding already holds a calculation.

Valiantangel
Junior Poster in Training
62 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

If this is a financial application where fractions of a cent are not allowed, then the simplest and safest approach is to store the amounts in integer cents. With float or double there are always going to be rare cases where rounding gives a slightly wrong result.
If you must use double, and you want to round down to 2 dec places, then mutliply by 100, use Math.floor(...) to round it down, then divide by 100 again.

JamesCherrill
Posting Genius
Moderator
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

It's just following the CORRECT rules of rounding.
If your value is 6.0749999, 6.07 would be displayed.
Since your value is 6.075, 6.08 is displayed.

hfx642
Posting Pro
515 posts since Nov 2009
Reputation Points: 248
Solved Threads: 105
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You