How to get the first digit of a float number in Swift

1 Answer

0 votes
//
// This program demonstrates how to extract the first digit
// of a floating‑point number in a clear and expressive way.
//
// Approach:
// - Convert the float to a string using String().
// - If the number is negative, skip the leading '-' sign.
// - Read the first numeric character.
// - Convert that character back into an integer.
//


/// Returns the first digit of a floating‑point number.
/// Works for both positive and negative values.
func firstDigit(of value: Double) -> Int {
    let text: String = String(value)

    // Skip the leading '-' for negative numbers
    let firstChar: Character =
        text.hasPrefix("-")
        ? text[text.index(text.startIndex, offsetBy: 1)]
        : text[text.startIndex]

    // Convert the character to an integer
    return Int(String(firstChar))!
}

/// Main execution block.
func main() {
    let f: Double = 376.287152

    let digit: Int = firstDigit(of: f)

    print(digit)
}

// Run the program
main()



/*
run:

3

*/

 



answered Sep 15 by avibootz
...