NABS
NABS

Reputation: 61

SWIFT: using / with some numbers results zero

in swift , when I say

x = 100 / 2 

it results 50, which is correct.

but when I say for example

66 / 130

It results zero, while it's supposed to be 0.50. It's actually

0.50769230769 

but I only need the two number after the .

is there a way where I can get this result?

Upvotes: 1

Views: 245

Answers (1)

l'L'l
l'L'l

Reputation: 47169

Use a format string with your number to manipulate how many decimal places to show:

var x:Float = 66 / 130
var y:Double = 66 / 130
print(String(format: "%.2f, %.2f", x, y))

Result:

0.51, 0.51

Other useful variations:

var x = 66 / 130 // 0.5076923076923077
var y = Double(round(1000 * x) / 1000) // 3 digits precision
print(y) // 0.508
print(floor(100 * y) / 100) // 0.5
print(ceil(100 * y) / 100) // 0.51
print(String(format: "%.2f", y)) // 0.51
print(String(format: "%.2f", floor(100 * y) / 100)) // 0.50
print(String(format: "%.2f", ceil(100 * y) / 100)) // 0.51

Using 3 digits precision then reducing to two digits allows you to control the floor and ceiling while at the same time having the desired amount of digits displayed after the decimal point.

Dropping the leading zero before the decimal point:

var t = String(format: "%.2f", ceil(100 * y) / 100)
print(String(t.characters.dropFirst())) // .51

Upvotes: 1

Related Questions