[英]How to remove decimal point if the number more than “10” in swift
How to remove decimal point value if the number is more than 10.0.如果数字大于 10.0,如何删除小数点值。 Below is the code what i have tried.
下面是我尝试过的代码。 At below code i am getting the value and i put the condition that if value is less than 1km then show number in meter, if value is more than 1 then show the number in km and if the value is greater than 10.0 then i am not able to remove the decimal point
在下面的代码中,我得到了值,我设置了条件,如果值小于 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
}
Ah the joys of C-style formatting strings.啊,C 风格格式化字符串的乐趣。
I present this as an alternative approach:我将此作为替代方法提出:
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)")
The output is output 是
100m
1.0km
10km
100km
This will accept Double
, Float
, Float80
, Float16
and any other type conforming to BinaryFloatingPoint
.这将接受
Double
、 Float
、 Float80
、 Float16
和任何其他符合BinaryFloatingPoint
的类型。
If you want localizable formats, look into NumberFormatter
.如果您想要可本地化的格式,请查看
NumberFormatter
。
[EDIT] as noted by @flanker in comments, LengthFormatter
with its method, string(from: String, unit: LengthFormatter.Unit) -> String
would be the way to go rather than NumberFormatter
[编辑] 正如@flanker 在评论中指出的那样,
LengthFormatter
及其方法, string(from: String, unit: LengthFormatter.Unit) -> String
将是 go 而不是NumberFormatter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.