Round like a Zero

C# (.NET Core), 19 bytes

n=>n.ToString("G1")

Try it online!

Examples:

Input     Output
----------------
 54321     5E+04
-56789    -6E+04
 99        1E+02
 0.23      0.2
 0.25      0.3
-0.25     -0.3
 4.56e23   5E+23
 4.56e-23  5E-23

Javascript, 19 bytes

x=>x.toPrecision(1)

MATL, 3 bytes

1&V

Try it online! Or verify all test cases.

Test case 0.25 fails for the compiler running in Octave on TIO, but works in Matlab on Windows:

enter image description here

The different behaviour is caused by Octave's/Matlab's sprintf function using either "banker's rounding" or ".5 away from zero" rounding, depending on platform. More information and tests can be found here.


For 6 bytes,

1t3$Yo

works both on Octave and on Matlab. Verify all test cases.

Tags:

Math

Code Golf