Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding Numbers to Two Significant Figures

Tags:

rounding

swift

I am sure this is an easy question to any of you are experienced in Swift, however, I just started learning how to program and have no idea where to start. What I am trying to do is a round a number to the nearest whole value, or to the third number. This is what I mean:

12.6 //Want rounded to 13
126 //Want rounded to 130
1264 //Want rounded to 1300

I know swift has a .rounded() function, and I have managed to use it to round the nearest 10th, 100th, etc., however, I cannot round the way I would like to. Any advice would be much appreciated.

like image 303
marco Avatar asked Jul 18 '17 18:07

marco


People also ask

How do you round to two significant figures?

look at the digit after the first non-zero digit if rounding to two significant figures. draw a vertical line after the place value digit that is required. look at the next digit. if it's 5 or more, increase the previous digit by one.

What does it mean to use 2 significant figures?

To determine the number of significant figures in a number use the following 3 rules: Non-zero digits are always significant. Any zeros between two significant digits are significant. A final zero or trailing zeros in the decimal portion ONLY are significant.

How do you write an answer in two significant figures?

You simply include all the significant figures in the leading number. For example, the number 450 has two significant figures and would be written in scientific notation as 4.5 × 102, whereas 450.0 has four significant figures and would be written as 4.500 × 102.


1 Answers

Here's one way to round any Double or Int (including negative numbers) to a given number of significant figures:

func round(_ num: Double, to places: Int) -> Double {
    let p = log10(abs(num))
    let f = pow(10, p.rounded() - Double(places) + 1)
    let rnum = (num / f).rounded() * f

    return rnum
}

func round(_ num: Int, to places: Int) -> Int {
    let p = log10(abs(Double(num)))
    let f = pow(10, p.rounded() - Double(places) + 1)
    let rnum = (Double(num) / f).rounded() * f

    return Int(rnum)
}

print(round(0.265, to: 2))
print(round(1.26, to: 2))
print(round(12.6, to: 2))
print(round(126, to: 2))
print(round(1264, to: 2))

Output:

0.27
1.3
13.0
130
1300

like image 76
rmaddy Avatar answered Sep 24 '22 19:09

rmaddy