...
| Code Block |
|---|
def ca1= ['1', '2', '.', '5'] as char[]
assert new BigDecimal( ca1 ) == 12.5
def ca2= [ 'a', 'b', '9', '3', '.', '4', '5', 'x', 'y', 'z' ] as char[]
assert new BigDecimal( ca2, 2, 5 ) == 93.45
//use 5 chars from the array beginning from index 2
|
Formatted Displays
There are some different ways of displaying a BigDecimal:
...
| Code Block |
|---|
[ 1.2345e7, 98.76e-3, 0.007, 0.000e4 ].each{
assert new BigDecimal( it.toString() ) == it
}
|
We can format integers and decimals using patterns with DecimalFormat:
| Code Block |
|---|
import java.text.*
def fmt= new DecimalFormat( '#,#00.0#' )
assert fmt.format( 5.6789d ) == '05.68'
//pattern says at least 2 digits before point
assert fmt.format( 12345L ) == '12,345.0'
//at least one digit after point, and comma as separator
|
We can explicitly define a text for negative numbers, separating the positive and negative formats with a semicolon. If the negative text is omitted, numbers are prefixed with the negative sign.
| Code Block |
|---|
import java.text.*
assert new DecimalFormat( '#,##0.00;(#,##0.00)' ).format( -56L ) == '(56.00)'
//pattern says parens around negative numbers
assert new DecimalFormat( '#,##0.00' ).format( -56L ) == '-56.00'
//same as '#,##0.00;-#,##0.00'
|
We can format decimal numbers:
| Code Block |
|---|
import java.text.*
assert new DecimalFormat( '0.###E0' ).format( 1234L ) == '1.234E3'
assert new DecimalFormat( '0.###E0;(0.###E0)' ).format( -0.001234 ) ==
'(1.234E-3)'
assert new DecimalFormat( '00.###E0' ).format( 0.00123 ) == '12.3E-4'
[ 12345: '12.345E3',
123456: '123.456E3'
].each{ assert new DecimalFormat( '##0.#####E0' ).format( it.key ) == it.value }
// '##0' in pattern means exponent will be a multiple of 3
|
We can change various settings using DecimalFormatSymbols:
| Code Block |
|---|
import java.text.*
def dfs= new DecimalFormatSymbols()
//use to give a different text for the exponent
assert dfs.zeroDigit == '0'
//char used for zero. Different for Arabic, etc
assert dfs.groupingSeparator == ','
//char used for thousands separator. Different for French, etc
assert dfs.decimalSeparator == '.' //char used for decimal point
assert dfs.digit == '#' //char used for a digit in a pattern
assert dfs.patternSeparator == ';'
//char used to separate positive and negative subpatterns in a pattern
assert dfs.infinity == '∞' //char used to represent infinity
assert dfs.minusSign == '-'
//char used for minus sign, used if no negative pattern specified
assert dfs.exponentSeparator == 'E'
//string used to separate mantissa and exponent
dfs.exponentSeparator= 'x10^'
def fmt= new DecimalFormat( '0.####E0', dfs )
assert fmt.format( 123456 ) == '1.2346x10^5'
//uses RoundingMode.HALF_EVEN by default
assert new DecimalFormat().format( Double.POSITIVE_INFINITY ) == '∞'
|
We'll look at DecimalFormats more in an upcoming tutorial on Internationalization.
Conversions
We can construct a BigDecimal from integers:
...