2

I tried almost all the solutions to round to decimals none of them working

(round(100 * 17.775)/100)

results I am getting is 17.77 I need 17.78 as a result of round

Please provide me the solution.

*NOTE : This question is only to round 17.775 means solution not working only for three decimals and 5 in the end [ending with 5 is creating problem only ] * Thanks in advance

Jawad Ali
  • 13,556
  • 3
  • 32
  • 49
  • Try `(17.775*100).rounded()/100` for rounded upto 2 decimals – Kishan Bhatiya Jan 30 '20 at 10:56
  • The problem is that 17.775 *cannot* be stored exactly in a binary floating point variable. Try this: `let x = 17.775 ; print(x - 17)` The output is 0.7749999999999986 – Martin R Jan 30 '20 at 10:58
  • 1
    The general problem is nicely explained here: [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Martin R Jan 30 '20 at 10:59

2 Answers2

1

Here is the solution check if last number is 5 or less than 5 and perform action accordingly

    let numberOfPlaces = 2.0
    let multiplier = pow(10.0, numberOfPlaces)
    let getLastNumberMultiplier = pow(10.0, numberOfPlaces+1)
    var num = 17.775
    let lastNumber = Int(num * getLastNumberMultiplier) % 10


    if lastNumber >= 5 {

        num = round(((num * multiplier ) + 1 ) ) / multiplier
    }
    else {

       num = round(num * multiplier) / multiplier
    }

    print(num)

enter image description here

enter image description here

Jawad Ali
  • 13,556
  • 3
  • 32
  • 49
  • Generally, answers are more helpful (to the author of the question and to future readers of this thread) if they *explain* the problem and the solution, instead of posting code only. – Martin R Jan 30 '20 at 12:07
  • This hides the problem only – 17.771 would be rounded to 17.78 as well. – Martin R Jan 30 '20 at 12:12
  • 2
    All this is still just *hiding* the real problem. (Note that `var num = 17.774999999999998` would also produce the output 17.78). – The real problem is that the number 17.775 *cannot* be represented as a binary floating point number, and that has to be solved first. OP might want to store the numbers differently (e.g. as a `Decimal`) but that is impossible to tell without further information. – Martin R Jan 30 '20 at 13:40
  • you are right @MartinR ... i gave woraround which is not pure i know – Jawad Ali Jan 30 '20 at 15:47
0

Guys I tried lot of answers and finally I got the solution from one of my friend

replacing 'round' to 'roundf' solved the problem

let neededAnswer = Double((roundf(100 * Float(db))/100)) 

this makes 17.775 to 17.78 and makes 17.774 to 17.77

I wanted this and this is the final answer.

Thank you guys for all your efforts and if you found any issues with this answer please add more answers/solutions and correct me.