Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round a number and make it show zeros?

Tags:

r

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.

like image 837
M. Er Avatar asked Feb 08 '17 05:02

M. Er


People also ask

How do I keep zeros after decimal in Excel?

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.

How do you show a number that is rounded?

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.

How do you show zeros after a decimal in Python?

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.


2 Answers

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)  

data

a <- 14.0034 
like image 129
akrun Avatar answered Oct 22 '22 00:10

akrun


Try this:

a = 14.0034  sprintf('%.2f',a) # 2 digits after decimal # [1] "14.00" 
like image 24
Sandipan Dey Avatar answered Oct 22 '22 01:10

Sandipan Dey