-1

I am writing in swift and I need to carry out code similar to this if myDouble ends in .33 { "carry out code"} How do I run a check on the decimal value of my number while ignoring the whole numbers? Thanks

ElectricTiger
  • 111
  • 1
  • 9
  • Wouldn't you need to round it first? 1/3 wouldn't end in .33, it actually never ends theoretically.. – ergonaut Oct 13 '15 at 00:25
  • this number is user defined from a text field so I need to add 0.01 to the number if they choose a number ending in .33 before I use the number in the rest of my calculations – ElectricTiger Oct 13 '15 at 00:29
  • 3
    Yea, your basic logic is flawed... What if the double "ends" in .330000000001 are you saying you wouldn't want to run the code in question? Because frankly, a double will never end in *exactly* .33. The structure of a Double won't allow it. – Daniel T. Oct 13 '15 at 00:29
  • Either convert it to a string, separate it at the "." and examine the decimal string part. Or this may help if you don't want to use Strings: http://stackoverflow.com/questions/31396301/getting-the-decimal-part-of-a-double-in-swift – myles Oct 13 '15 at 00:32
  • Do something like: `if fabs(fabs(myDouble) - floor(fabs(myDouble)) - 0.33) < 0.001`. Adjust `0.001` to whatever accuracy you are looking for. – vacawama Oct 13 '15 at 00:45

3 Answers3

2
let myDouble = 10.0/3  //  3.333333333333333

if String(format: "%.2f", myDouble).hasSuffix(".33") {
    print(true)
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
0

Just do abs(myDouble - floor(myDouble)), that will get your decimal value. then do any rounding or formatting needed to handle infinite 3's or what not

Make sure you import Foundation, it's required to use floor: import Foundation

Charles Truluck
  • 961
  • 1
  • 7
  • 28
Knight0fDragon
  • 16,609
  • 2
  • 23
  • 44
0
let double = 4.3391762
let newDouble = String(format: "%.03f", double)
let thirtyThree = abs(Double(newDouble)! - floor(Double(double))) * 100

floor(thirtyThree)

Probably could be refactored but there's one way.

Aaron
  • 6,466
  • 7
  • 37
  • 75