Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.


Code Block
[        0.0f: '0x0.0p0',
      (-0.0f): '0x0.0p0', //no negative sign in hex string rep'n of -0.0f
         1.0f: '0x1.0p0', //most returned strings begin with '0x1.' or '-0x1.'
         2.0f: '0x1.0p1',
         3.0f: '0x1.8p1',
         5.0f: '0x1.4p2',
      (-1.0f): '-0x1.0p0',
         0.5f: '0x1.0p-1',
        0.25f: '0x1.0p-2',
          (Float.MAX_VALUE): '0x1.fffffep127',
          (Float.MIN_VALUE): '0x0.000002p-126',
                       //low values beginning with '0x0.' are called 'subnormal'
  (Float.NEGATIVE_INFINITY): '-Infinity',
                (Float.NaN): 'NaN',
].each{ k, v->
  assert Float.toHexString(k) == v

We can format integers and decimals using String.format():

Code Block

//Integers ('d')
assert String.format('%d', 45) == '45'
assert String.format('%5d,%1$5o', 46L) == '   46,   56'
    //octal format; each minimum 5 chars wide; use an argument twice
assert String.format('%-4d,%<-5x', 47g) == '47  ,2f   '
    //hex format without leading '0x'; left-justified with '-';
    //shortcut ('<') for using argument again
assert String.format('%2d,%<1X', 123) == '123,7B'
    //hex in uppercase with capital 'X'
assert String.format('%04d', 34) == '0034' //zero-pad
assert String.format('%,5d', 12345) == '12,345' //use grouping-separators
assert String.format('%+3d,%2$ 3d', 123L, 456g) == '+123, 456'
    //always use plus sign; always use a leading space
assert String.format('%(3d', -789 as short) == '(789)' //parens for negative
assert String.format('%(3o,%2$(3x,%3$(3X', 123g, 456g, -789g) == '173,1c8,(315)'
    //neg octal/hex only for BigInteger

//Floating-Point ('f', 'a', 'e', 'g')
assert String.format('e = %f', Math.E) == 'e = 2.718282'
    //default 'f' format is 7.6
assert String.format('e=%+6.4f', Math.E) == 'e=+2.7183'
    //precision is digits after decimal point
assert String.format('$ %(,6.2f', -6217.58) == '$ (6,217.58)'
    //'(' flag gives parens, ',' uses separators
assert String.format('%a, %A', 2.7182818f, Math.PI) ==
    '0x1.5bf0a8p1, 0X1.921FB54442D18P1' //'a' for hex
assert String.format('%+010.4a', 23.25d) == '+0x001.7400p4'
    //'+' flag always includes sign; '0' flag zero-fills
assert String.format('%e, %10.4e', Math.E, 12345.6789) ==
    '2.718282e+00, 1.2346e+04' //'e' for scientific format
assert String.format('%(10.5E', -0.0000271) == '(2.71000E-05)'
assert String.format('%g, %10.4G', Math.E, 12345.6789) == '2.71828,  1.235E+04'
    //'f' or 'e', depending on input

Floating-Point Arithmetic

We can perform the same basic operations that integers and BigDecimal can: