# Posted By

hansamann on 02/02/07

# Statistics

Viewed 587 times
Favorited by 2 user(s)

# Groovy Series: Numbers

/ Published in: Groovy  `//the two most common number classesdef intObj = 5assert intObj.class.name == 'java.lang.Integer' def bigDecimalObj = 5.12345assert bigDecimalObj.class.name == 'java.math.BigDecimal' //you can explicitly create Long, Float and Double with L / F / Ddef longObj = 20Lassert longObj.class.name == 'java.lang.Long'def floatObj = 40.45Fassert floatObj.class.name == 'java.lang.Float'def doubleObj = 34.45Dassert doubleObj.class.name == 'java.lang.Double' //if G is used, it checks if the number has a decimal point, then creates a BigInteger or BigDecimaldef bigIntegerObj = 50Gassert bigIntegerObj.class.name == 'java.math.BigInteger' //some coercion stuff//multiplication, addition and substraction between two floats results in a doubledef z = 2F * 2Fassert z.class.name == 'java.lang.Double' //multiplication, addition and substraction with BigInteger or BigDecimal results in BigInteger or BigDecimaldef product = 1.1G * 2 //BigDecimal and Integerassert product.class.name == 'java.math.BigDecimal' (3G*4).class.name == 'java.math.BigInteger' //BigInteger and Integer //multiplication of two integersassert (5*4).class.name == 'java.lang.Integer' //multiplication with Longassert (1L*4).class.name == 'java.lang.Long' //dividing some numbers(5/5).class.name == 'java.math.BigDecimal'//if you want an integer, use the intdiv() method(5.intdiv(5)).class.name == 'java.lang.Integer'(1.intdiv(5)).class.name == 'java.lang.Integer' //result is 0assert 1/2 == 0.5  //some GDK methods for numbers//think about a java for loop... you don't need it!def numbers = []10.times { numbers << it } //it will contain values from 0 to 9assert numbers.join(",") == '0,1,2,3,4,5,6,7,8,9'10.upto(12) { numbers << it}assert numbers.join(",") == '0,1,2,3,4,5,6,7,8,9,10,11,12'11.downto(10) { numbers << it}assert numbers.join(",") == '0,1,2,3,4,5,6,7,8,9,10,11,12,11,10' numbers = []1.step(2, 0.1) { numbers << it; assert it.class.name == 'java.math.BigDecimal' }assert numbers.join(",") == '1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9' //notice 2 is not included numbers = []1.0.step(2, 0.1) { numbers << it; assert it.class.name == 'java.math.BigDecimal' }assert numbers.join(",") == '1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9' //notice how the first value changed to 1.0` Subscribe to comments