Link to home
Start Free TrialLog in
Avatar of earlmoore
earlmoore

asked on

Ridding Myself from Trailing Digits on Dollar Amts

I'm trying to get a dollar amount in the format of $xx.xx.  Using the double datatype, when I multiply two numbers, sometimes I get a format of $xx.00000000007.  I know its stupid, but how can I restrict the output to only two digits after the decimal point?
Avatar of earlmoore
earlmoore

ASKER

Edited text of question
One way to do this would be to ues a long instead of a double to represent your dollar amount.  This long would then represent the total number of cents.
Whenever I need to deal with dollars, I avoid float and double like the plague. When you multiply and divide, you can easily get results that are ever so slightly off. I have found it far better to stick with int or long. Multiply the dollar values, add 50 and divide by 100 for a rounded result. (Add 0 to truncate, and 99 to round high).
Output can be done with something like:

StringBuffer dv=new StringBuffer(Integer.toString(dlr));
dv.insert(dv.length()-2,'.');
String dlrstr=dv.toString();

This produces the right string, and could be captured in some utility method.


ASKER CERTIFIED SOLUTION
Avatar of threshold
threshold

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial