W
W
Waksim2018-06-28 15:15:09
Swift
Waksim, 2018-06-28 15:15:09

How to output number to console without .0?

Hello!
I use Xcode 9.4.1, Playground, Swift 4

Task example:

var a, b, c : Double
c = a/b                              // с = 10.0 / 2.0 = 5.0
print("Осталось \(c) яблок")         // Осталось 5.0 яблок


Question: How to get rid of ".0" when outputting an integer of Double type.
Just the Int() conversion is not suitable, because there are also fractional results in the problems (c = 5.7) .

Is it possible to implement this without converting to string and trimming the regular expression?

Searched the net with no results. I would appreciate any help, thanks in advance

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Babin, 2018-06-28
@chiliec

print("Осталось \(String(format: "%g", c)) яблок")

F
Farwisdomer, 2018-06-28
@Farwisdomer

extension Double
{
    func truncate(places : Int)-> Double
    {
        return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question