round

operator

Library: Floating point number support (OMFLOAT)
Import : omfloat.xmd
Library: Binary coded decimal numbers (OMBCD)
Import : ombcd.xmd

Returns: a BCD or floating point number rounded to the nearest value


Declaration
export overloaded external float function
 round value float x
 nearest value float base optional
export overloaded bcd function
 round value bcd b
 nearest value bcd base optional
 bankers-nearest value bcd bankers-base optional


Purpose

Use this function to round any of the following to the nearest digit or decimal place specified:

  • a BCD number
  • a floating point number
  • an integer coerced into a BCD or floating point number

If you do not specify the precision, you will round to the nearest integer. If a base precision is specified, the value is rounded to the nearest multiple of the precision specifier. If bankers-base is specified, the value is rounded to the nearest even multiple of the precision specifier.

Import either ombcd.xmd or omfloat.xmd in your program after deciding whether you want BCD mathematics (excellent for financial calculations) or floating point mathematics (excellent for extremely large numbers).

BCD Example:

Calculate the area of a circle:

 import "ombcd.xmd" unprefixed
 process
 local bcd pi initial {"3.14179"}
 local bcd radius initial {"74"}
 local bcd area
 
 set area to round (pi * radius * radius)
 output "area of circle with radius " || "d" % radius || " = " || "d" % area || "%n"

Floating Point Example:

Calculate the area of a circle:

 import "omfloat.xmd" unprefixed
 process
 local float radius initial {"74"}
 local float area
 
 set area to round (pi * radius * radius)
 output "Area of circle with radius " || "d" % radius || " = " || "d" % area || "%n"

You can specify the precision of the rounding. The following program uses a precision of 0.01 to round to the nearest cent:

 
 import "ombcd.xmd" unprefixed
 process
 local bcd exchange-rate initial {1.4356}
 local bcd us-price initial {129.95}
 local bcd canadian-price
 
 set canadian-price to round (us-price * exchange-rate) nearest bcd 0.01
 output "US " || "<,ドルNNZ.ZZ>" % us-price || " = " || "<,ドルNNZ.ZZ>" % canadian-price || " CDN %n"

You can use bankers rounding (available only with the BCD library) to resolve ties to the nearest even multiple of the precision specifier:

 ; Bankers-nearest rounds to the nearest even digit
 import "ombcd.xmd" unprefixed
 process
 local bcd x initial {9.95}
 local bcd y initial {9.85}
 local bcd rounded-x
 local bcd rounded-y
 set rounded-x to round (x) bankers-nearest 0.1
 set rounded-y to round (y) bankers-nearest 0.1
 output "Rounded-x = "
 || "d" % rounded-x
 || "%n"
 || "Rounded-y = "
 || "d" % rounded-y
 || "%n"
 ; Output: "Rounded-x = 10
 ; Rounded-y = 9.8"

The precision specifier must be a power of 10, or an error occurs.

Related Topics
Other Library Functions

AltStyle によって変換されたページ (->オリジナル) /