Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,227 questions

56,129 answers

573 users

How to convert a decimal to int64 in Swift

1 Answer

0 votes
import Foundation

/*
    ============================================================
    Convert a decimal-like value to Int64 in Swift.

    This program demonstrates:
      • Conversion using rounded(), which rounds to the nearest integer.
      • Conversion using Int64(value), which truncates toward zero.
      • Conversion using Decimal + NSDecimalNumber for strict conversion.
      • Helper functions that print all conversion styles.

    Notes:
      • Swift does not have a built-in "long" type; Int64 is the closest.
      • rounded() returns a Double; cast to Int64 afterward.
      • Int64(value) truncates the fractional part.
      • Decimal → Int64 conversion is done via NSDecimalNumber.
    ============================================================
*/

// Rounds a Double to Int64
func convertDoubleToInt64(_ value: Double) -> Int64 {
    return Int64(value.rounded())
}

// Truncates a Double to Int64
func castDoubleToInt64(_ value: Double) -> Int64 {
    return Int64(value)
}

// Converts Decimal using truncation
func convertDecimalToInt64(_ value: Decimal) -> Int64 {
    return NSDecimalNumber(decimal: value).int64Value
}

// Converts Decimal strictly (throws if fractional or out of range)
func convertDecimalExact(_ value: Decimal) -> String {
    let number = NSDecimalNumber(decimal: value)
    do {
        let exact = try number.int64ValueExact()
        return "\(exact)"
    } catch {
        return "ERROR — fractional or out of range"
    }
}

// Prints conversion styles for Double
func showDoubleConversions(_ value: Double) {
    print("Input decimal (Double): \(value)")
    print("Rounded (rounded): \(convertDoubleToInt64(value))")
    print("Truncated (Int64 cast): \(castDoubleToInt64(value))")
    print()
}

// Prints conversion styles for Decimal
func showDecimalConversions(_ value: Decimal) {
    print("Input decimal (Decimal): \(value)")
    print("Truncated (int64Value): \(convertDecimalToInt64(value))")
    print("Exact (int64ValueExact): \(convertDecimalExact(value))")
    print()
}

extension NSDecimalNumber {
    // Throws if fractional or out of range
    func int64ValueExact() throws -> Int64 {
        if self.decimalValue != Decimal(self.int64Value) {
            throw NSError(domain: "ExactConversion", code: 1, userInfo: nil)
        }
        return self.int64Value
    }
}

func main() {
    // Double examples
    showDoubleConversions(12.7)
    showDoubleConversions(12.3)
    showDoubleConversions(-5.8)
    showDoubleConversions(42.0)

    // Decimal examples
    showDecimalConversions(Decimal(string: "12.7")!)
    showDecimalConversions(Decimal(string: "42")!)
    showDecimalConversions(Decimal(string: "-5.8")!)
}

// Call main manually
main()



/*
run:

Input decimal (Double): 12.7
Rounded (rounded): 13
Truncated (Int64 cast): 12

Input decimal (Double): 12.3
Rounded (rounded): 12
Truncated (Int64 cast): 12

Input decimal (Double): -5.8
Rounded (rounded): -6
Truncated (Int64 cast): -5

Input decimal (Double): 42.0
Rounded (rounded): 42
Truncated (Int64 cast): 42

Input decimal (Decimal): 12.7
Truncated (int64Value): 12
Exact (int64ValueExact): ERROR — fractional or out of range

Input decimal (Decimal): 42
Truncated (int64Value): 42
Exact (int64ValueExact): 42

Input decimal (Decimal): -5.8
Truncated (int64Value): -5
Exact (int64ValueExact): ERROR — fractional or out of range

*/

 



answered Aug 6 by avibootz
...