1

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)
jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • 1
    Assuming you also want to be able to do some floating point math, you probably just want to determine if the number is a [whole] integer and if so, display it as such. This should get you on your way: https://stackoverflow.com/questions/31396301/getting-the-decimal-part-of-a-double-in-swift – jnpdx Jul 29 '22 at 01:54
  • 1
    The formatting of the output of `print` is unimportant, as it is not user-facing. You should worry only about the strings that the user _sees_. – matt Jul 29 '22 at 02:14
  • Is this for a little script/tool/utility, or an end user application (where localization correctness is critical)? – Alexander Jul 29 '22 at 02:15

4 Answers4

1

Consider using .formatted() to format the floating point number properly for you:

import Foundation

  ⋮
  ⋮
  ⋮

print(total.formatted())
Ranoiaetep
  • 5,872
  • 1
  • 14
  • 39
0

you could just do this:

 print(String(format:"%0.0f", total))
0
  • 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)!)
Quang Hà
  • 4,613
  • 3
  • 24
  • 40
  • 1
    For the `NumberFormatter`, consider using `.formatted()` instead. You can use `.formatted(.number.precision(.fractionLength(0)))` or `.formatted(.number.rounded(increment: 1))` to specify the precision if needed. – Ranoiaetep Jul 29 '22 at 03:13
  • ah https://developer.apple.com/documentation/foundation/measurement/3816389-formatted this is new api since ios 15. i didn't know that – Quang Hà Jul 29 '22 at 03:59
-2

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)