skip to Main Content

Below is my code.. I am doing 5 + 2 and I would like the output to be 7 but I am getting 7.0. Can someone please help me and tell me why

var runningNumber:Double = 5
var currentValue:Double = 2
var total:Double = Double(runningNumber + currentValue)
print(total)

4

Answers


  1. Chosen as BEST ANSWER

    I got it working but changing the code to this

    import UIKit
    
    var runningNumber:Double = 5.3
    var currentValue:Double = 2
    var total:String =  NSNumber(value: runningNumber + currentValue).stringValue
    
    print(total)
    

  2. you could just do this:

     print(String(format:"%0.0f", total))
    
    Login or Signup to reply.
  3. Consider using .formatted() to format the floating point number properly for you:

    import Foundation
    
      ⋮
      ⋮
      ⋮
    
    print(total.formatted())
    
    Login or Signup to reply.
    • Use Ints instead of Doubles
    let two = 2
    let five = 5
    print(two + five)
    
    • Cast to Int when printing
    let two: Double = 2
    let five: Double = 5
    print(Int(two + five))
    
    • Format to a string with zero fraction digits
    let two: Double = 2
    let five: Double = 5
    print(String(format: "%.0f", two + five))
    
    • Use NumberFormatter
    let two: Double = 2
    let five: Double = 5
    
    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    formatter.maximumFractionDigits = 0
    
    let sum = NSNumber(value: two + five)
    print(formatter.string(from: sum)!)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search