Do you want this for handling currency (money) amounts?
If you're handling money, you should never use a float or double. Instead, use a long, and store the number of 100ths of a penny (or cent, or whatever). That is €14.65 becomes 146500.
Reasons:
* Floating point numbers are inexact, and prone to bizarre rounding errors. Integers are precise.
* When performing calculations on money, you sometimes need two extra decimal places, to avoid compounding rounding errors. This is usual for currency conversions, or when adding tax.
Another thing to think about with money is that rounding is frequently banker's rounding. That is, if the fractional part is exactly 0.5, then you round up or down, ensuring that the result is an even number. This tends to balance out rounding errors since, in this case, rounding up or down are equally valid.
Example code:
PHP Code:
private static String moneyToString(long money) {
boolean negative = money < 0;
if (negative) {
money = -money;
}
// round
int fraction = (int) money % 100;
money /= 100;
if (fraction > 50 || (fraction == 50 && money % 2 == 1)) {
money++;
}
StringBuffer s = new StringBuffer(Long.toString(money));
// pad
while (s.length() < 3) {
s.insert(0, '0');
}
// insert decimal place
s.insert(s.length() - 2, '.');
// add sign
if (negative) {
s.insert(0, '-');
}
return s.toString();
}
Graham.