data <- c(28.9899,23.565444,98.8999,34.8788)
The expected output is: 28.98, 23.56, 98.89, 34.87
By using a button: Select the cells that you want to format. On the Home tab, click Increase Decimal or Decrease Decimal to show more or fewer digits after the decimal point.
If we want to round 4.732 to 2 decimal places, it will either round to 4.73 or 4.74. 4.732 rounded to 2 decimal places would be 4.73 (because it is the nearest number to 2 decimal places). 4.737 rounded to 2 decimal places would be 4.74 (because it would be closer to 4.74).
I suggest you load the siunitx package and create a dedicated macro, using the macro um that's provided by the siunitx package, to achieve your formatting objectives. Note that rounding to two digits is performed automatically, as well as setting , (a comma) as the output decimal marker. As inputs, both , or . are OK as the decimal markers.
You may be better off using the decimal type, and the multiplication will fail if it would result in a number larger than the max value for a double. My advice: stop using double in the first place. If you need decimal rounding then odds are good you should be using decimal. What is your application?
Note that rounding to two digits is performed automatically, as well as setting , (a comma) as the output decimal marker. As inputs, both , or . are OK as the decimal markers. Show activity on this post. Another option is the numprint package and its command prounddigits {}, which is switched off by pnoround.
To simply "truncate" a number, bcdiv ($var, 1, 2); where 2 is the number of decimals to preserve (and 1 is the denomenator - dividing the number by 1 allows you to simply truncate the original number to the desired decimal places) This turns out to be more elusive than one might think.
Basic R floor
function doesn't allow decimal number so let's define
floor_decimal <- function(x, level=1) round(x - 5*10^(-level-1), level)
then by
floor_decimal(data,2)
returns
[1] 28.98 23.56 98.89 34.87
Assuming this is for displaying purpose you may use regex to extract data only till 2 decimal places.
sub('(\\d+\\.\\d{2}).*', '\\1', data)
#[1] "28.98" "23.56" "98.89" "34.87"
Cut unwanted digits using regex and re-convert to numeric:
as.numeric(sub("(.*\\.\\d{2}).*", "\\1", data))
[1] 28.98 23.56 98.89 34.87
We could use trunc()
:
trunc(data*100)/100
Output:
[1] 28.98 23.56 98.89 34.87
library(stringi)
data<- c(28.9899,23.565444,98.8999,34.8788)
as.numeric(stri_sub(data,1,5))
output
28.98 23.56 98.89 34.87
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With