RingJavafor Ring

Numbers

Ring numbers are doubles. Java has int, long, double, BigDecimal and BigInteger. This lesson shows how they meet.

What you will learn#

The program#

samples/UsingJava/tutorials/ch03_numbers.ring
# Tutorial 3: numbers - int, long, double, BigDecimal, BigInteger and Math
load "java.ring"

using {
	"java.lang"
	"java.math"
	"java.text"
}

RoundingMode = new RoundingMode
BigInteger = new BigInteger

# Ring numbers are doubles; Java has more kinds. A Ring number goes where Java wants int, long or double
? Math.abs(-7)
? Math.sqrt(144)
? Math.pow(2,10)
? Math.floorMod(-7,3)
? Math.round(2.5)
? Math.hypot(3,4)

# the limits of the types
? Integer.MAX_VALUE
? Long.parseLong("123456789012") + 1

# parsing and writing numbers
? Integer.parseInt("123") + 1
? Integer.toBinaryString(10)
? Integer.toHexString(255)
? Integer.parseInt(["ff",16])
? Double.parseDouble("2.5") * 2

# a Java long: a Ring number is exact up to 9,007,199,254,740,992; jLong makes a Java long when a method wants one
? Long.@toString(jLong(123456789012))

# money must not use doubles: BigDecimal is exact
oPrice = new BigDecimal("19.99")
oQty = new BigDecimal("3")
oTotal = oPrice.multiply(oQty)
? oTotal.toString()
oTax = oTotal.multiply(new BigDecimal("0.0825")).setScale([2,RoundingMode.HALF_UP])
? oTax.toString()
? 0.1 + 0.2
? (new BigDecimal("0.1")).add(new BigDecimal("0.2")).toString()

# BigInteger has no limit: 30 factorial
oFact = BigInteger.ONE
for nI = 2 to 30
	oFact = oFact.multiply(BigInteger.valueOf(jLong(nI)))
next
? oFact.toString()

# formatting
oFormat = new DecimalFormat("#,##0.00")
? oFormat.format(1234567.891)
Output
7
12
1024
2
3
5
2147483647
123456789013
124
1010
ff
255
5
123456789012
59.97
4.95
0.30
0.3
265252859812191058636308480000000
1,234,567.89

How it works#

A Ring number is a double. The bridge converts it to the type that the Java method wants, if it fits. A double is exact for whole numbers up to 9,007,199,254,740,992; for a larger Java long use jLong(text).

Never keep money in a double: 0.1 + 0.2 is not 0.3. BigDecimal holds decimal numbers exactly, and BigInteger has no upper limit (30 factorial fits). String.format("%,.2f", x) and DecimalFormat write numbers for people.

Exercises#

  1. Print 50 factorial with BigInteger.
  2. Show that 0.1 + 0.2 differs from 0.3 in Ring and is equal with BigDecimal.
  3. Print Integer.MAX_VALUE + 1 as a long.

Next#

Collections and streams

RingJava - use Java classes and methods from Ring programs.