简体   繁体   中英

How to remove comma from string 1,398.90 using groovy

I am not able to remove comma from string 1,398.90 using groovy

def liveprice = '1,398.90'; def liveprice2 = liveprice.replaceAll(',', '')

I would really avoid using regular expressions with numbers

Especially numbers that look like money 💰

You can use DecimalFormat to read that String into a BigDecimal (so you keep precision)

import java.text.*

BigDecimal result = DecimalFormat.instance.with {
    parseBigDecimal = true
    parse('1,398.90')
}

As mentioned by @daggett, your code works fine. Another alternative way besides regex or replace:

'1,39,9,,,,.90'.split(",").join()
// outputs: 1399.90

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM