0

I'm trying to save and retrieve a float datatype into Firebase. I am able to save just fine and have it structured like below.

Firebase Screenshot

However, when I attempt to retrieve the value using the code

for child in snapshot.children.allObjects as! [FDataSnapshot] {

            let rating = child.value["rating"] as? Float
            print(rating)

I'm getting the following:

Optional(8.19999981)

Optional(8.69999981)

Optional(9.19999981)

What is the best way to prevent this from occurring?

FortuneFaded
  • 1,259
  • 4
  • 20
  • 28

1 Answers1

7

Firebase doesn't directly support the float type. Numeric representations are support by NSNumber, so in general either save your number as a string or wrap it into an NSNumber when saving and reverse that when reading back in.

let p = 3.14159265
let n = NSNumber(float: Float(p))

print(n)

There are lots of alternatives as well.

Jay
  • 34,438
  • 18
  • 52
  • 81
  • ah awesome, I hadn't realized that. Worked perfectly, thank you! – FortuneFaded May 06 '16 at 01:10
  • wait, actually it's still occurring randomly... I'm saving it as let rating = NSNumber(float: (Float(ratingInput))!) and am retrieving it in the same way as above except with as! NSNumber – FortuneFaded May 06 '16 at 01:47
  • I ended up just rounding it using this method [http://stackoverflow.com/questions/27338573/rounding-a-double-value-to-x-number-of-decimal-places-in-swift](http://stackoverflow.com/questions/27338573/rounding-a-double-value-to-x-number-of-decimal-places-in-swift) – FortuneFaded May 06 '16 at 02:35