Mohammed Nabil
Mohammed Nabil

Reputation: 157

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. 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

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
            }

Upvotes: 0

Views: 320

Answers (1)

Chip Jarred
Chip Jarred

Reputation: 2795

Ah the joys of C-style formatting strings.

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

100m
1.0km
10km
100km

This will accept Double, Float, Float80, Float16 and any other type conforming to BinaryFloatingPoint.

If you want localizable formats, look into 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

Upvotes: 2

Related Questions