从double中删除小数点,并在整数中保留小数值

时间:2021-04-18 17:11:11

for example let's just say I have a:

例如,让我说我有一个:

var num: double = 123.123

How can I get an Integer of : 123123

我如何获得整数:123123

4 个解决方案

#1


0  

let num: Double = 123.123
print(Int(String(num).stringByReplacingOccurrencesOfString(".", withString: "")))

#2


1  

You can use a NSNumberFormatter:

您可以使用NSNumberFormatter:

let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.decimalSeparator = ""

let a = 123.132
let b = formatter.stringFromNumber(a)

this returns a String, to cast to Int you can:

这会返回一个String,要转换为Int,你可以:

if let b = formatter.stringFromNumber(a) {
    let c = Int(b)
}

#3


0  

You can convert it into the string and remove "." and convert it to Integer. Simple

您可以将其转换为字符串并删除“。”并将其转换为整数。简单

let num: Double = 123.123
var stringNum : String = String(num)
stringNum = stringNum.stringByReplacingOccurrencesOfString(".", withString: "")
let finalInt = Int(stringNum)

Hope this helps :)

希望这可以帮助 :)

#4


0  

Simply do

let value = 100.155
print(value) // 100.155 
let str = String(value) 
print(str) //100.155

let newValue = Int(str.stringByReplacingOccurrencesOfString(".", withString: "")) 
print(newValue)// Optional(100155) . unwrap it 
print(newvalue!) // 100155

#1


0  

let num: Double = 123.123
print(Int(String(num).stringByReplacingOccurrencesOfString(".", withString: "")))

#2


1  

You can use a NSNumberFormatter:

您可以使用NSNumberFormatter:

let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.decimalSeparator = ""

let a = 123.132
let b = formatter.stringFromNumber(a)

this returns a String, to cast to Int you can:

这会返回一个String,要转换为Int,你可以:

if let b = formatter.stringFromNumber(a) {
    let c = Int(b)
}

#3


0  

You can convert it into the string and remove "." and convert it to Integer. Simple

您可以将其转换为字符串并删除“。”并将其转换为整数。简单

let num: Double = 123.123
var stringNum : String = String(num)
stringNum = stringNum.stringByReplacingOccurrencesOfString(".", withString: "")
let finalInt = Int(stringNum)

Hope this helps :)

希望这可以帮助 :)

#4


0  

Simply do

let value = 100.155
print(value) // 100.155 
let str = String(value) 
print(str) //100.155

let newValue = Int(str.stringByReplacingOccurrencesOfString(".", withString: "")) 
print(newValue)// Optional(100155) . unwrap it 
print(newvalue!) // 100155