Skip to main content
Code Review

Return to Revisions

2 of 2
advice to avoid stringly typed variables
200_success
  • 145.6k
  • 22
  • 190
  • 479

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);
 }
}
200_success
  • 145.6k
  • 22
  • 190
  • 479
default

AltStyle によって変換されたページ (->オリジナル) /