Floating point data type: formatting

You can format floating point numbers by using formatting commands.

To format a float as a string of digits, use the format operator, %.

The following program outputs the string "-120.65":

  ; float-format.xom
  import "omfloat.xmd" unprefixed
  process
      local float quantity
      set quantity to -120.65
      output "d" % quantity
  ; Output: "-120.65"

You can pad the output string with spaces on the right side using the "f" format modifier along with a number indicating the total size of the output string. The following code will output [-53.17 ].

  ; float-pad.xom
  import "omfloat.xmd" unprefixed
  process
      local float quantity
      set quantity to -53.17
      output "[" || "8fd" % quantity || "]"
  ; Output: "[-53.17  ]"

If you specify a number smaller than the number of digits in the number, digits to the right of the decimal will be truncated as necessary to fit the field width specified. If the number of digits in the number is greater than the field width after all digits to the right of the decimal point (and the decimal point itself) have been truncated, the whole number portion will be printed in full.

You can force the padding to occur on the left instead of the right by adding the "k" format modifier. The following code outputs [ -53.17].

  ; float-pad-left.xom
  import "omfloat.xmd" unprefixed
  process
      local float quantity
      set quantity to -53.17
      output "[" || "8fkd" % quantity || "]"
  ; Output: "[  -53.17]"

Note that command-based formatting does not provide a means of rounding fractional amounts for display. To display fewer than 16 digits to the right of the decimal point, you should round the number first using the round function:

  ; float-round.xom
  import "omfloat.xmd" unprefixed
  process
      local float quantity
      set quantity to 9.56789
      output "d" % round quantity by 0.001
  ; Output: "9.568"

The code above will output:

  9.568

The following demonstrates how to use "d" % to produce a character representation of the speed of light:

  ; float-format-d.xom
  import "omfloat.xmd" unprefixed
  process
    local float LightSpeed initial {299792458}
  ;     LightSpeed is in meters per second. 
    local float LightKmPerYear
    set LightKmPerYear to ((LightSpeed * 60 * 60 * 24 * 365.25) / 1000)
    output "The speed of light in kilometers per year: " 
           || "d" % LightKmPerYear   
           || "%n" 
  ; Output: "The speed of light in kilometers per year: 9460730472580.801"

This code produces the following result: The speed of light in kilometers per year: 9460730472580801000

The "d" format item for floating point numbers supports the same modifiers as for BCD numbers:

  • e: format number in exponential (scientific) notation
  • u: uppercase the formatted number (NAN,INF,9+E9)
  • l: lowercase the formatted number (nan,inf,9+e9)
  • k: pad on the left
  • <arg>f: pads to <arg> characters