Spock Web Console

subscribe to the feed Subscribe
Integer to BigDecimal Conversion (via #spockwebconsole)
tweet this script Tweet

Integer to BigDecimal Conversion

Published 2 months ago by Bl_nK
Actions  ➤ Edit In Console Back To Console Show/Hide Line Numbers View Recent Scripts
import spock.lang.*

class Util {
    static BigDecimal convertIntegerToBigDecimal(BigInteger balance, Integer precision) {
        String balanceAsPaddedString = balance.toString().padLeft(precision + 1, '0')
        List balanceAsList = balanceAsPaddedString.split("")
        Integer insertAt = balanceAsList.size() - precision
        BigDecimal balanceAsBigDecimal = new BigDecimal(balanceAsList.plus(insertAt, '.').join()).setScale(precision)
        return balanceAsBigDecimal
    }
}

@Unroll
class UtilSpec extends Specification {
  def "Try conversion of integer to big decimal"() {
    expect:
    Util.convertIntegerToBigDecimal(i,p) == bd

    where:
    i|p|bd
    500|8|0.00000500
    3|6|0.000003
    75433242|6|75.433242
  }
}