Overview:
Using you language of choice, implement a complete "half away from 0" rounding function in the shortest amount of code possible.
Rules/Constraints:
- Direct, predefined
Round
-like functions are not allowed. Floor
/Ceiling
-type functions are allowed, if your language supports these.- Function shall be able to handle 32-bit floating-point values.
- Function shall be able to correctly handle negative values (see examples).
- This is Golf, so shortest code wins.
- Correct rounding for this challenge is to round away from 0, such that a rounded value will have an equal or larger absolute value.
Input/Output:
- Your function shall take two parameters:
- The first is a float
x
, which is the value to round. - The second is an integer
n
, which is the number of decimal places to round to. x
can be a whole number or contain a decimal part, fitting within a 32-bit, single-precision float.n
can be greater than or equal to 0, and may be larger than the number of decimal places inx
.
- The first is a float
- Output will be the correctly rounded
x
. - *In cases where the solution is not exactly representable in IEEE float format, the output should be the logical representation you would have figured if not using a computer. i.e. The output of
Round(0.125, 2)
should be0.13
.
Example I/O:
Round(1.23456789, 7)
1.2345679
Round(1.234, 5)
1.234 OR 1.23400 (Your choice on trailing 0)
Round(-0.5, 0)
-1 NOT 0
Round(-0.123, 2)
-0.12 NOT -0.13
Round(3.1415926535897932384626433832, 20)
3.14159265358979323846
Winning:
**Some system limitations may be present which make your function less accurate/usable. In these cases, supply the best possible calculation you can within those limitations.
For example, I have a solution in my preferred environment, VBA in Office 2003, which only allows me to round up to 307 digits, while the IDE will only let me use values up to 15 significant decimal places. (I will eventually post this example here.)
With your answer submission, please post the highest values of n
and the largest number of significant decimal digits for x
for which your function will run. If you cannot meet the minimum requirements, that solution is disqualified, no matter the code length. (i.e. my own solution described above is invalid)
While this is code golf, and the shortest code will generally win. If two answers exist with different maximum values for x
and n
, the solution which works with the highest input values (measured as x * n
) will win. If these two solutions meet the same limitation while fulfilling the requirements of the challenge, then the shortest code of those two will win.
If no solutions meet the requirement, then the best limitation score (shortest code length in the event of a tie) will win.
Example submission given the rules above for my own code:
<CODE HERE>
Max n = 307
Max x digits = 15
Limitation Score (x * n) = 4605
1.23456789
is again for example only. \$\endgroup\$