如果 swift 中的数字大于“10”,如何删除小数点

How to remove decimal point if the number more than "10" in swift

如果数字大于 10.0,如何删除小数点值。以下是我尝试过的代码。在下面的代码中,我得到了这个值,我提出的条件是,如果值小于 1km,则以米为单位显示数字,如果值大于 1,则以 km 为单位显示数字,如果值大于 10.0,则我不是可以去掉小数点

let resultDelivery = String(format: "%.1f", Obj.distance)// Here getting value from api either i get 0.5 or 6.5 or 11.5
            if (resultDelivery.starts(with: "0")){
                let resultDelivery2 = String(format: "%.f", Obj.distance/1 * 1000)
                cell.lblDeliverykm?.text = resultDelivery2.description + " " + "m".Localized() + "  " + "" // result is 900 m
            }
            else if (resultDelivery.starts(with: "10.0")){
                let resultDelivery2 = String(format: "%.0f", Obj.distance)
                cell.lblDeliverykm?.text = resultDelivery2.description + " " + "km".Localized() + "  " + "" // couldn’t able to remove decimal point 
            }
            else {
                cell.lblDeliverykm?.text = resultDelivery.description + " " + "km".Localized() + "  " + "" // result is 8.6 km
            }

啊,C 风格格式化字符串的乐趣。

我将此作为替代方法提出:

extension String.StringInterpolation
{
    public mutating func appendInterpolation<F: BinaryFloatingPoint>(distance: F)
    {
        if distance < 1 {
            appendLiteral("\(Int(distance * 1000))m")
        }
        else if distance >= 10 {
            appendLiteral("\(Int(distance))km")
        }
        else
        {
            let d = (distance * 10).rounded(.toNearestOrEven) / 10
            appendLiteral("\(d)km")
        }
    }
}


print("\(distance: 0.1)")
print("\(distance: 1)")
print("\(distance: 10)")
print("\(distance: 100)")

输出为

100m
1.0km
10km
100km

这将接受 DoubleFloatFloat80Float16 和任何其他符合 BinaryFloatingPoint.

的类型

如果您想要可本地化的格式,请查看 NumberFormatter

[EDIT] 正如@flanker 在评论中指出的那样,LengthFormatter 及其方法,string(from: String, unit: LengthFormatter.Unit) -> String 将是要走的路,而不是 NumberFormatter