16
Satisfying Rounding
You know when you're in science class, and asked to round to 2 sig figs, but your answer is 5.2501...
? You should round to 5.3
, but that's just so unsatisfying! By rounding to 5.3
, you're off by a whole 0.05, which is a large amount compared to 0.1 (the place value you're rounding to)! So help me round in a satisfying way.
To round in a satisfying way, you must round at the first digit you come across that produces a relatively small error - less than half of the maximum error possible when rounding. Basically, you need to round whenever you encounter 0, 1, 8, or 9. If that never happens, return the input as is. Do not round on leading zeroes or ones - that just doesn't feel satisfying.
Input
A string or float value that represents a nonnegative decimal number.
Output
The same decimal number rounded satisfactorily, in either string or float format.
Examples
Input -> Output
0 -> 0
0.5 -> 0.5
0.19 -> 0
0.8 -> 1
5.64511 -> 5.645
18.913 -> 20
88.913 -> 100
36.38299 -> 36.4
621 -> 620
803.22 -> 1000
547.4726 -> 547.4726
This is a code-golf challenge, so shortest code wins!
Sandbox – Quintec – 2018-12-08T15:11:32.700
Are strings such as
036.40000
considered a valid output? – Arnauld – 2018-12-08T16:08:07.2331Can we assume that a
.0
part will be given for integers? Also,0
isn't positive. – Erik the Outgolfer – 2018-12-08T16:08:56.650@EriktheOutgolfer No, you may not - also thanks, changed to nonnegative. – Quintec – 2018-12-08T17:03:17.563
@Arnauld No leading nor trailing zeroes, since that kind of defeats the purpose of rounding. – Quintec – 2018-12-08T17:04:02.357
Is a missing leading
0
acceptable if the integer part is0
? – Erik the Outgolfer – 2018-12-08T17:13:33.003@EriktheOutgolfer Sure. – Quintec – 2018-12-08T17:20:01.887
1So
19
rounds to20
but0.19
rounds to0
? Why? – Neil – 2018-12-08T19:38:30.793Actually, my code had a bug, and now rounding them as per the question now makes my code golfer, so never mind. – Neil – 2018-12-08T19:48:11.630
Floating point ought not to be allowed as an input format. Consider the input
"6.68"
. Clearly the answer is6.7
. But if you parse6.68
as a 64-bit floating point you get6.67999999999999971578290569595992565155029296875
and the output would become6.68
! – feersum – 2018-12-09T11:48:42.347