It seems like you tried to use NumberFormat
but gave up on the idea. You should take advantage of it — after all, that's what the standard library is there for.
Furthermore, I would split the parsing and the currency conversion into two separate functions.
You should avoid "stringly typed" variables. Once you parse the string into a number, hang on to the number, not the string. Convert back into string form as late as possible, just for presentation purposes.
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class CR38317 {
public static BigDecimal parseCurrency(String value) throws ParseException {
// Pick a suitable locale. GERMANY, for example, uses the 1.234,56 format.
// You could call .getCurrencyInstance() instead, but then it will
// require the value to contain the correct currency symbol at a
// specific position.
NumberFormat fmt = NumberFormat.getNumberInstance(Locale.GERMANY);
// By default, fmt.parse() returns a Number that is a Double.
// However, some decimals, such as 0.10, cannot be represented
// exactly in floating point, so it is considered best practice to
// use BigDecimal for storing monetary values.
((DecimalFormat)fmt).setParseBigDecimal(true);
return (BigDecimal)fmt.parse(value);
}
public static BigDecimal convertCurrency(BigDecimal inValue, String inCurrency, String outCurrency) {
// TODO: Derive the conversion rate from the currencies
return inValue.multiply(new BigDecimal(50));
}
public static void main(String[] args) throws ParseException {
BigDecimal in = parseCurrency("1.234,56");
BigDecimal out = convertCurrency(in, "EUR", "INR");
System.out.println("In = " + in);
System.out.println("Out = " + out);
}
}
\\.
by,
, change last,
and replace all,
by empty string? Why you can't immediately replace.
by empty string and after that replace,
by.
if it exists? \$\endgroup\$Double
(and floating point in general) does not store exact amounts like people expect - ie,.1
can't be represented (only something really close). This can lead to surprising results, which tends to make people itchy when it involves money. You're also storing the amount in a string, which means you have to convert it each time. For money, you want to use something based off/backed byBigDecimal
, so you get the values you're expecting. \$\endgroup\$