1

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?

NABS
  • 61
  • 1
  • 2
  • 8
  • Where are the input values coming from and how are you trying to use the result? You should be calculating with float if you want fractional parts. – Wain Nov 15 '15 at 10:07
  • when I convert it to float it gives me an error saying that x += 35 – NABS Nov 15 '15 at 10:09
  • it says that += can't be applied on double – NABS Nov 15 '15 at 10:10
  • 10
    `100 / 2` results zero and you think that's correct? – Sulthan Nov 15 '15 at 10:15
  • See: [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/27341001#27341001) – zisoft Nov 15 '15 at 10:39

1 Answers1

1

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
l'L'l
  • 44,951
  • 10
  • 95
  • 146