-1

So i want to parse my string that contains value with currency, for example:

€579,976
€0
$1.5

Currently i am just removing the first char and trying to parse the rest.

Does anyone have an idea how to do it in a better way?

Som Bhattacharyya
  • 3,972
  • 35
  • 54
david hol
  • 1,272
  • 7
  • 22
  • 44

1 Answers1

2

You could use a regular expression to solve that problem. There is a Unicode Character Property for Currencies : \p{Sc}.

Usage Example, currency and amount:

val amountAndCurrencyRe = "(\\p{Sc})(.*)".r

val results = amountAndCurrencyRe.findAllIn("""€579,976  
  €0 
  $1.5
  ¥20
""")

results.collect{ 
 case amountAndCurrencyRe(currency,amount) =>
   println(s"Amount:$amount Currency:$currency") 
}.toList

Result:

scala> results.collect{ case amountAndCurrencyRe(currency,amount) => println(s"Amount:$amount Currency:$currency") }.toList
Amount:579,976  Currency:€
Amount:0 Currency:€
Amount:1.5 Currency:$
Amount:20 Currency:¥
res6: List[Unit] = List((), (), (), ())

just get Amounts:

scala> "€579,976  €0 $1.5 ¥20".replaceAll("\\p{Sc}","")
res1: String = 579,976  0 1.5 20
Andreas Neumann
  • 10,734
  • 1
  • 32
  • 52