将字符串值从服务器格式化为Double转换为Int [英] Convert String Values From Server Formatted as Double To Int

查看:113
本文介绍了将字符串值从服务器格式化为Double转换为Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个服务,该服务发回类型为 String 的值,其中包含浮点,如 Double ,因为例如1240.86。
我想将它转换为 Int 当我尝试转换为 Int(stringObject)当值具有浮点时,强制转换失败。
我该如何施展它?
谢谢!

Im working with a service that send back values of type String which contains floating point like Double as so for example "1240.86". I want to cast it to Int and when i try to convert like so Int(stringObject) the cast fails when the values have floating points. How can i cast it? Thanks!

推荐答案

分两步尝试:

if let aDouble = Double(someString) {
    let someInt = Int(aDouble)
}

或可能:

let someInt = Int(Double(someString) ?? 0)

虽然后者有点像kludge,因为你可能不想强迫值 0 如果字符串不是有效数字。

though the latter is a bit of a kludge since you probably don't want to force a value of 0 if the string isn't a valid number.

这篇关于将字符串值从服务器格式化为Double转换为Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆