1

I was playing with the floats and explicit conversion of the floats into desired types. What I'm getting is when you convert a float into string, there is some junk data that comes along. Why is that happening ?

Heres my code :

let a:Float = 5.23

var fName = "john"
var lName = "doe"
var fullName = fName + lName
var mixedString = fullName + String(a)
print(mixedString)

This gives johndoe5.23000001907349 as output. What is going on here with the extra 1907349

Ateev Chopra
  • 1,026
  • 2
  • 15
  • 32
  • Consider the bit depth and how it limits the accuracy. There is an unlimited range of real numbers and only limited bits for storage. That accounts for all current computer system. – Volker Jun 03 '14 at 17:21
  • possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Lily Chung Jun 03 '14 at 17:21

1 Answers1

0

The Float type isn't terribly precise, so you're getting a little extra garbage from the imprecision. If you omit the Float type declaration, you'll get a Double instead, which won't have this problem.

let a = 5.23

var fName = "john"
var lName = "doe"
var fullName = fName + lName
var mixedString = fullName + String(a)
print(mixedString)
// prints "johndoe5.23"
Nate Cook
  • 92,417
  • 32
  • 217
  • 178
  • You can also declare a as a `Double` explicitly: `let a: Double = 5.23` – Nate Cook Jun 03 '14 at 17:24
  • But doesn't this create security problems ? – Ateev Chopra Jun 03 '14 at 17:25
  • How would that create security problems? A double and a float both represent floating point numbers, the double just has twice as many bits to hold the number, so you get a lot more precision (and range). There shouldn't be any security impact of using one type over the other. – Nate Cook Jun 03 '14 at 17:27
  • I guess he meant using Float and getting 5.23000001907349 instead of 5.23 causes security problems. – Gokhan Arik Jun 03 '14 at 17:57
  • @GokhanArik Yes. Thats what i meant. Its storing garbage value. So it can be a security threat ? – Ateev Chopra Jun 03 '14 at 18:22
  • I suppose from the perspective that results are less predicable due to the lower precision, it could be a security issue. You certainly shouldn't use a `Float` as an iterator. In any case, in Swift at least, `Double` is the preferred type for floating-point values. – Nate Cook Jun 04 '14 at 23:38