Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

round double to 0.5

Tags:

rounding

swift

i have a result "1.444444" and i want to round this result to "1.5" this is the code i use :

a.text = String(round(13000 / 9000.0))

but this is round to "1.0" and i need round to "1.5"

and this code :

a.text = String(ceil(13000 / 9000.0))

is round to "2.0"

like image 624
Tzahi Avatar asked Dec 25 '15 07:12

Tzahi


People also ask

What does correct to the nearest 0.5 mean?

Nearest 0.5 kg means consider the mass in 0.5 kg lumps, hence: ..., 42.5, 43.0, 43.5, 44.0, 44.5, 45.0, 45.5, 46.0, 46.5, ... So which of these values is nearest to 45 kg?

How do I round to 0.5 in Javascript?

roundHalf(0.6) => returns 0.5.

How do you round to half?

When rounding to the nearest half, round the fraction to whichever half the fraction is closest to on the number line. If a fraction is equally close to two different halves, round the fraction up.

How do you round a double in C#?

Round(Double, Int32, MidpointRounding) This method is used to rounds a double precision floating-point value to a specified number of fractional digits. A parameter specifies how to round the value if it is midway between two numbers.


2 Answers

Swift 3:

extension Double {
    func round(nearest: Double) -> Double {
        let n = 1/nearest
        let numberToRound = self * n
        return numberToRound.rounded() / n
    }

    func floor(nearest: Double) -> Double {
        let intDiv = Double(Int(self / nearest))
        return intDiv * nearest
    }
}

let num: Double = 4.7
num.round(nearest: 0.5)      // Returns 4.5

let num2: Double = 1.85
num2.floor(nearest: 0.5)     // Returns 1.5

Swift 2:

extension Double {
    func roundNearest(nearest: Double) -> Double {
        let n = 1/nearest
        return round(self * n) / n
    }
}

let num: Double = 4.7
num.roundNearest(0.5)      // Returns 4.5
like image 147
atxe Avatar answered Oct 31 '22 09:10

atxe


x = 13000 / 9000.0;

denominator = 2;
a.text = String(round(x*denominator )/denominator );

First convert 1.444 to 2.888, then round to 3.0 and then divide by 2 to get 1.5. In this case, the denominator of 0.5 is 2 (i.e. 1/2). If you want to round to nearest quarter (0.25,0.5, 0.75, 0.00), then denominator=4

I Should point out that this works perfectly if the denominator is a power of 2. If it is not, say denominator=3, then you can get weird answers like 1.99999999 instead of 2 for particular values.

like image 26
Mark Lakata Avatar answered Oct 31 '22 10:10

Mark Lakata