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

时间:2016-08-11 07:06:07

标签: ios swift

例如,让我说我有一个:

var num: double = 123.123

如何获得整数:123123

4 个答案:

答案 0 :(得分:1)

您可以使用NSNumberFormatter

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

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

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

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

答案 1 :(得分:0)

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

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

希望这会有所帮助:)

答案 2 :(得分:0)

简单地做

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

答案 3 :(得分:0)

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