Search code examples
groovyready-api

Remove last zero digits in groovy in ReadyApi


I am trying to remove the last zero digits in groovy in my ReadyApi test.

For example,

273.900 needs to be 273.9

17.580 needs to be 17.58

116.000 needs to be 116

I have the following but this is not complete:

def qTY = context.expand( '${Stock DataSource#QTY}' )
qTY = qTY.replaceAll('.000', '')
qTY = qTY.replaceAll('00', '')
return qTY

Could someone help me tp write this more efficient? Thank you


Solution

  • You can use relatively simple regex for this:

    '273.002000'.replaceFirst( /((?<=(\..{0,20}))0+)$/, '' ).replaceFirst( /\.$/, '' )
    

    prints

    273.002