3

I'm developing Android app which uses this method:

public static String currencyFormat(BigDecimal n) {
    return NumberFormat.getCurrencyInstance().format(n);
}

which formats number based on Locale currency.

How to revert back from currency format, e.g. $35, to 35? Note that I cannot just remove First character because different locales have different currency name lengths.

leonz
  • 1,107
  • 2
  • 10
  • 32
  • 1
    You need to store the currency symbol separately. Either that, or use a String as your input (which I don't recommend). You can't use a BigDecimal as your input with your currency, because that will just give you the unicode value appended to the currency amount. – Stephan Branczyk Jun 26 '16 at 19:21
  • Well this code I gave works well, but it's true I can't use BigDecimal for converting back because the string would have currency characters in it. I have an idea though. Is there a way to get a string which represents the currency of your locale? then I can just do string.replaceAll(currency, ""); – leonz Jun 26 '16 at 19:36

2 Answers2

1

You must store the currency unit in a separate field, encapsulated into some higher-order abstraction such as a final value class (with appropriate equals and hashcode defined), eg called CurrencyAmount. [if you do scala, basically you want a case class]. Any other solution will require you to 'reverse engineer' the unit portion from the amount portion and depending on the complexity of your spec of allowable values, it might be reliable only to various degrees. I would just encode the two portions in their own fields and solve this for all cases.

Creos
  • 2,445
  • 3
  • 27
  • 45
0

You might try to cut out all non numeric characters from a String with a regex.

Try this.

Community
  • 1
  • 1
R. Zagórski
  • 20,020
  • 5
  • 65
  • 90
  • That is the problem, string is a mathematic expression which might have "sin", "cos" and so on in it. – leonz Jun 26 '16 at 19:33