Doubles और Floats
let name = 3.14 // Double
let name: Float = 3.14 // less precise
let result = Double(intValue) / doubleValue
Declaring Doubles
Double Swift का default floating-point type है, अपने आप उपयोग होता है जब एक literal में एक decimal point हो।
उदाहरण: Declaring Doubles
// Declare a constant `price`, set to `19.99`
let price = 19.99
// Declare a constant `taxRate`, set to `0.08`
let taxRate = 0.08
// Print "Price: \(price), tax rate: \(taxRate)" to the console
print("Price: \(price), tax rate: \(taxRate)")
Login to try C/C++/Java/PHP code in the editor
Float vs Double
Float कम memory उपयोग करता है (32 bits) लेकिन Double (64 bits) से कम precision रखता है। Swift default रूप से Double infer करता है, इसलिए Float को एक explicit annotation से मांगना चाहिए।
उदाहरण: Float vs Double
// Declare a constant `preciseValue` (a Double), set to `3.14159265358979`
let preciseValue: Double = 3.14159265358979
// Declare a constant `lessPrecise` (a Float), set to `3.14159265358979`
let lessPrecise: Float = 3.14159265358979
// Print "Double: \(preciseValue)" to the console
print("Double: \(preciseValue)")
// Print "Float: \(lessPrecise)" to the console
print("Float: \(lessPrecise)")
Login to try C/C++/Java/PHP code in the editor
Converting Between Int and Double
Swift numeric types के बीच कभी चुपचाप convert नहीं करता; आपको एक value को explicitly wrap करना चाहिए, जैसे Double(someInt), calculations के लिए एक integer को एक floating-point number में convert करने के लिए।
Double(items) के बिना, एक Double को एक Int से divide करना compile भी नहीं होता -- Swift matching types चाहता है।उदाहरण: Converting Between Int and Double
// Declare a constant `items`, set to `3`
let items = 3
// Declare a constant `totalCost`, set to `10.0`
let totalCost = 10.0
// Declare a constant `average`, set to `totalCost / Double(items)`
let average = totalCost / Double(items)
// Print "Average cost per item: \(average)" to the console
print("Average cost per item: \(average)")
Login to try C/C++/Java/PHP code in the editor
- Arithmetic के बाद दो
Doublevalues को==से compare करना और exact equality की उम्मीद करना, जब floating-point rounding उन्हें थोड़ा अलग बना सकता है। Doubleका इरादा होने परFloatउपयोग करना;DoubleSwift का default है और ज़्यादा precision रखता है, इसलिए इन्हें mix करने के लिए explicit conversion चाहिए।- दो
Intvalues को divide करना एक decimal result की उम्मीद से, यह भूल जाना किInt / IntएकDoubleproduce करने के बजाय truncate करता है।
Doubleएक 64-bit floating-point type है और decimal numbers के लिए Swift का default choice है।Floatएक 32-bit floating-point type है, कम precise लेकिन कभी-कभी memory save करने के लिए उपयोग होता है।- Floating-point arithmetic में छोटी rounding errors हो सकती हैं, इसलिए exact
==comparisons से बचें। - एक
Intको एकDoubleमें convert करने के लिए एक explicitDouble(someInt)call चाहिए।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: