View source: R/round_preserve_sum.R
round_preserve_sum | R Documentation |
Sometimes, the sum of rounded numbers (e.g., using base::round()
) is not
the same as their rounded sum.
round_preserve_sum(x, digits = 0)
x |
Numerical vector to sum. |
digits |
Number of decimals for rounding. |
This solution applies the following algorithm
Round down to the specified number of decimal places
Order numbers by their remainder values
Increment the specified decimal place of values with k largest remainders, where k is the number of values that must be incremented to preserve their rounded sum
A numerical vector of same length as x
.
https://biostatmatt.com/archives/2902
sum(c(0.333, 0.333, 0.334))
round(c(0.333, 0.333, 0.334), 2)
sum(round(c(0.333, 0.333, 0.334), 2))
round_preserve_sum(c(0.333, 0.333, 0.334), 2)
sum(round_preserve_sum(c(0.333, 0.333, 0.334), 2))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.