Groovy web console

subscribe to the feed Subscribe
to this
site

Testing rounding problem

Published 4 months ago by Alvaro
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import java.math.RoundingMode
import java.text.DecimalFormat

DecimalFormat decimalFormat = new DecimalFormat("#.##")
decimalFormat.setRoundingMode(RoundingMode.DOWN)
def initialValue = 45.8
def quantity = 3

def unitPrice = (initialValue/quantity)
def roundedUnitPrice = decimalFormat.format(unitPrice).toDouble()
total = roundedUnitPrice * quantity
missingRound = initialValue - total
decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN)
roundedMissingRound = decimalFormat.format(missingRound).toDouble()

println("initialValue: ${initialValue}")
println("quantity: ${quantity}")
println("unitPrice: ${unitPrice}")
println("roundedUnitPrice: ${roundedUnitPrice}")
println("missingRound: ${missingRound}")
println("roundedMissingRound: ${roundedMissingRound}")

List<Map> itemList = []
for(int i = 0; i < 3; i++) {
   def itemMap = [
        Price: decimalFormat.format(4.14 + roundedUnitPrice).toDouble(),
        Quantity: 1,
        QuantityUOM: 4
   ]

if (itemList.isEmpty()) {
    itemMap.Price = decimalFormat.format(itemMap.Price + roundedMissingRound)
}
itemList.add(itemMap)
}

println(itemList)