Float.round
round
, go back to Float module for more information.
Specs
round(float(), precision_range()) :: float()
Rounds a floating-point value to an arbitrary number of fractional digits (between 0 and 15).
The rounding direction always ties to half up. The operation is performed on the binary floating point, without a conversion to decimal.
This function only accepts floats and always returns a float. Use
Kernel.round/1
if you want a function that accepts both floats
and integers and always returns an integer.
Known issues
The behaviour of round/2
for floats can be surprising. For example:
iex> Float.round(5.5675, 3)
5.567
One may have expected it to round to the half up 5.568. This is not a bug. Most decimal fractions cannot be represented as a binary floating point and therefore the number above is internally represented as 5.567499999, which explains the behaviour above. If you want exact rounding for decimals, you must use a decimal library. The behaviour above is also in accordance to reference implementations, such as "Correctly Rounded Binary-Decimal and Decimal-Binary Conversions" by David M. Gay.
Examples
iex> Float.round(12.5)
13.0
iex> Float.round(5.5674, 3)
5.567
iex> Float.round(5.5675, 3)
5.567
iex> Float.round(-5.5674, 3)
-5.567
iex> Float.round(-5.5675)
-6.0
iex> Float.round(12.341444444444441, 15)
12.341444444444441