Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a number with specified level of precision?

Tags:

format

r

I would like to create a function that returns a vector of numbers a precision reflected by having only n significant figures, but without trailing zeros, and not in scientific notation

e.g, I would like

somenumbers <- c(0.000001234567, 1234567.89)
myformat(x = somenumbers, n = 3)

to return

[1] 0.00000123  1230000

I have been playing with format, formatC, and sprintf, but they don't seem to want to work on each number independently, and they return the numbers as character strings (in quotes).

This is the closest that i have gotten example:

> format(signif(somenumbers,4), scientific=FALSE)
[1] "      0.000001235" "1235000.000000000"
like image 945
Abe Avatar asked Mar 07 '11 22:03

Abe


People also ask

What is precision number?

Precision is the number of digits in a number. Scale is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a precision of 5 and a scale of 2.

How do I print a specific digit of a number in Python?

To print a number with a specific number of significant digits we do this: print '{0:1.3g}'. format(1./3.) print '{0:1.3g}'.

What is numeric format example?

Numeric data types can be instructed to format and parse scientific notation only via a pattern. In a pattern, the exponent character immediately followed by one or more digit characters indicates scientific notation. Example: "0. ###E0" formats the number 1234 as "1.234E3".

How do you print number format in Python?

To specify a level of precision, we need to use a colon ( : ), followed by a decimal point, along with some integer representing the degree of precision. We place this inside the curly braces for an f-string, after the value we want to format.


2 Answers

You can use the signif function to round to a given number of significant digits. If you don't want extra trailing 0's then don't "print" the results but do something else with them.

> somenumbers <- c(0.000001234567, 1234567.89) 
> options(scipen=5)
> cat(signif(somenumbers,3),'\n')
0.00000123 1230000 
> 
like image 90
Greg Snow Avatar answered Oct 07 '22 21:10

Greg Snow


sprintf seems to do it:

sprintf(c("%1.8f", "%1.0f"), signif(somenumbers, 3))
[1] "0.00000123" "1230000"
like image 21
Ista Avatar answered Oct 07 '22 20:10

Ista