The common code in R for rounding a number to say 2 decimal points is:
> a = 14.1234 > round(a, digits=2) > a > 14.12
However if the number has zeros as the first two decimal digits, R suppresses zeros in display:
> a = 14.0034 > round(a, digits=2) > a > 14
How can we make R to show first decimal digits even when they are zeros? I especially need this in plots. I've searched here and some people have suggested using options(digits=2)
, but this makes R to have a weird behavior.
Use the pound sign to prevent extra zeroes. The symbol # is another placeholder character in custom formats. This will prevent all leading zeroes if used at the front of the number, and prevent all trailing zeroes if used after the decimal point. For example, the custom format 00.
A wavy equals sign (≈: approximately equal to) is sometimes used to indicate rounding of exact numbers, e.g., 9.98 ≈ 10. This sign was introduced by Alfred George Greenhill in 1892.
Use the format() function to add zeros to a float after the decimal, e.g. result = format(my_float, '. 3f') . The function will format the number with exactly N digits following the decimal point.
We can use format
format(round(a), nsmall = 2) #[1] "14.00"
As @arvi1000 mentioned in the comments, we may need to specify the digits
in round
format(round(a, digits=2), nsmall = 2)
a <- 14.0034
Try this:
a = 14.0034 sprintf('%.2f',a) # 2 digits after decimal # [1] "14.00"
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