I'm having a surprising amount of difficulty in trying to format some numbers with errors. I can't find any previous attempts to do this here or elsewhere and it would surely be of use to the community.
I have some number-error pairs: {12345.6789, 0.0012345}
which I would like to convert to strings with both the number and the error rounded to the same number of decimal places, such that the error has a precision of two significant figures.
f[{12345.6789, 0.03456}]
f[{12345.6789, 3.456}]
f[{12345.6789, 345}]
"12345.679 ± 0.035"
"12345.7 ± 3.5"
"12340 ± 350"
I'm struggling to get this done with RealDigits
, N
, NumberForm
, StringRiffle
and others.
Can anyone produce a robust working implementation of f
?
Edit: Additional test cases
There are quite a few subtly different behaviours when handling different number, including rounding, adding trailing zeros, handling precision = 0, and probably others. Therefore for the sake of comprehensively testing implementations here are a list of inputs and the required outputs (if you can think of any additional useful test cases then let me know / add them):
f[{12.3456, 0.0123}] -> "12.346 ± 0.012"
f[{12.3456, 0.123}] -> "12.35 ± 0.12"
f[{129.3456, 1.23}] -> "129.3 ± 1.2"
f[{-129.3456, 12.3}] -> "-129. ± 12."
f[{12.9999, 0.02}] -> "13.000 ± 0.020"
f[{1, 100}] -> "0 ± 100."
f[{-1, 100}] -> "0 ± 100."
f[{12345.6789, 345}] -> "12350. ± 340."
f[{12345.6789, 3456}] -> "12300. ± 3500."
Around
$\endgroup$