0

I have following numbers in CGFloat

  1. 375.0
  2. 637.0
  3. 995.0

I need to get the first number in CGFloat data type. For example the result for #1 must be 3.0, for #2 must be 6.0 and #3 must be 9.0

I tried the following

let width:CGFloat = 375.0
// Convert Float To String
let widthInStringFormat = String(describing: width)
// Get First Character Of The String
let firstCharacter = widthInStringFormat.first
// Convert Character To String
let firstCharacterInStringFormat = String(describing: firstCharacter)
// Convert String To CGFloat
//let firstCharacterInFloat = (firstCharacter as NSString).floatValue
//let firstCharacterInFloat = CGFloat(firstCharacter)
//let firstCharacterInFloat = NumberFormatter().number(from: firstCharacter)

Nothing seems working here. Where am I going wrong?

Update

To answer @Martin R, find below my explanation

I am implementing a grid-view (like photos app) using UICollectionView. I want the cells to be resized based on screen size for iPhone/iPad, Portrait and Landscape. Basically I don't want fixed columns. I need more columns for larger screen sizes and lesser column for smaller screen sizes. I figured that perhaps I can decide based on screen width. For example if the screen width is 375.0 then display 3 columns, If somewhere around 600 then display 6 columns, if around 1000 then display 10 columns and so on with equal width. So what I came up with is a) decide columns based on first number of the screen size and then for width divide by actual screen width. For example for a screen width of 375.0 I will have a cell size of CGSize(width: screenWidth / totalColumn) and so on.

Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207

2 Answers2

1
 var floatNum:CGFloat = 764.34
    var numberNeg = false
    if floatNum < 0{
        floatNum = -1.0 * floatNum
        numberNeg = true
    }
    var intNum = Int(floatNum)
    print(intNum) //764
    while (intNum>9) {
        intNum = Int(intNum/10)
    }
    floatNum = CGFloat(intNum)
    if numberNeg {
        floatNum = -1.0 * floatNum
    }
    print(intNum)//7
    print(floatNum)//7.0

try this one ...I hope it'll work

Pradeep Kashyap
  • 921
  • 10
  • 15
1

You said:

For example if the screen width is 375.0 then display 3 columns, If somewhere around 600 then display 6 columns, if around 1000 then display 10 columns and so on with equal width.

So what you really want is not the first digit of the width (which would for example be 1 for width = 1024 instead of the desired 10) but the width divided by 100 and rounded down to the next integral value:

let numColumns = (width / 100.0).rounded(.down)

Or, as an integer value:

let numColumns = Int(width / 100.0)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382