What is the simplest way to estimate the nearest rounding, where we know the rounding is always e.g. 100, 10, 1, 0.1 etc. We don’t necessarily know the original number.
8 => 1 // we have rounded to the nearest *one*
88 => 1
80 => 10 // we have rounded to the nearest *ten*
4530 => 10
4000 => 1000 // we have rounded to the nearest *thousand*
0.024 => 0.001
0.02 => 0.01
0.024332 => 0.000001
4000.7 => 0.1 // we have rounded to the nearest *tenth*
This might be useful when, given one number, we want to round all other numbers by the same quantity. Thanks.
I am seeking to determine for any number, if we assume that the number has been rounded, how can we estimate what that rounding amount is?
For instance, given the number 4000, we estimate the number we started with was rounded to the nearest thousand. But given 4000.7, we estimate that the rounding was to the nearest tenth.
2
Answers
Raymond Chen has got this right - you cannot do this in a mathematical fashion, because of issues with floating point representations. So, you need a string-based function.
For integers we can use a RegEx to count the number of trailing zeros n, and the rounding will be 10^n.
For non-integers, we need the number of numbers n after the decimal point, again something we can do with RegEx. The rounding will be the inverse of 10^n.
This is possibly a bit scrappy, but the idea is basically to find where the first thing that isn’t zero is from the right and return a number based on that.