07-18-2023, 09:58 PM
For many applications, you need exact number of decimal places to round.
For some others, you do not have such a constraint and want to "compress" output size, but still want to avoid converting number to strings (and vice versa later) like in exporting JSON having millions of numbers.
In that case you may use 'trick' to round significand (mantissa), not whole number. In such a case you will end up with final decimal places
and most of numbers will still have at most e.g. 3 decimal places (if needed) preserved while some will have slightly more.
This is what you might expect with this approach while still working with decimal numbers:
> 5.2472
>
> 5.2516
>
> 5.2556
>
> 5.26
>
> 5.264
instead of:
>5.24731462499949
>
>5.251488374999099
>
>5.25566283399894
>
>5.259839374999501
>
>5.264012208999702
let value = 5.24731462499949
print(value)
// 5.24731462499949
let valueSignificandRounded = round((1000 * 10) * value.significand) / (1000 * 10)
let valueRounded = CGFloat(sign: v.sign, exponent: v.exponent, significand: valueSignificandRounded)
print(valueRounded)
// 5.2472
For some others, you do not have such a constraint and want to "compress" output size, but still want to avoid converting number to strings (and vice versa later) like in exporting JSON having millions of numbers.
In that case you may use 'trick' to round significand (mantissa), not whole number. In such a case you will end up with final decimal places
and most of numbers will still have at most e.g. 3 decimal places (if needed) preserved while some will have slightly more.
This is what you might expect with this approach while still working with decimal numbers:
> 5.2472
>
> 5.2516
>
> 5.2556
>
> 5.26
>
> 5.264
instead of:
>5.24731462499949
>
>5.251488374999099
>
>5.25566283399894
>
>5.259839374999501
>
>5.264012208999702
let value = 5.24731462499949
print(value)
// 5.24731462499949
let valueSignificandRounded = round((1000 * 10) * value.significand) / (1000 * 10)
let valueRounded = CGFloat(sign: v.sign, exponent: v.exponent, significand: valueSignificandRounded)
print(valueRounded)
// 5.2472