Print Double as Int - if not a Double value

2020-07-25 09:28发布

问题:

I want my Double to display as an Int, if the value is an integer - otherwise as a Double.

Example;

var Value = Double()

.

Value = 25.0 / 10.0

Now I want Value to display 2.5 (when inserted to label)

.

Value = 20.0 / 10.0

Now I want Value to display 2 - and NOT 2.0

回答1:

One classic way is to establish a value for epsilon which represents your tolerance for considering a value close enough to an Int:

// How close is close enough to be considered an Int?
let kEPSILON = 0.0001

var val = 1.9999
var str: String

if abs(val - round(val)) < kEPSILON {
    str = String(Int(round(val)))
} else {
    str = String(val)
}

print(str)  // "2"


回答2:

One approach is to obtain the fractional part using % operator, and check if it is zero:

let stringVal = (Value % 1 == 0)
?  String(format: "%.0f", Value)
:  String(Value)


回答3:

I like dasblinkenlight's and vacawama's answers, but also want to contribute another one: Using NSNumberFormatter

let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.alwaysShowsDecimalSeparator = false

let string0 = formatter.stringFromNumber(25.0/10.0)!
let string1 = formatter.stringFromNumber(20.0/10.0)!

print(string0)
print(string1)

result:

2.5
2

The most important advantage: It is localized. On german devices it will show 2,5 instead of 2.5, just as it would be expected by a german speaking user.



回答4:

To display numbers as text, use NSNumberFormatter(). You can set its minimumFractionDigits property to zero:

let fmt = NSNumberFormatter()
fmt.minimumIntegerDigits = 1
fmt.maximumFractionDigits = 4
fmt.minimumFractionDigits = 0

print(fmt.stringFromNumber(25.0 / 10.0)!)  // 2,5
print(fmt.stringFromNumber(20.0 / 10.0)!)  // 2
print(fmt.stringFromNumber(2.0 / 7.0)!)    // 0,2857

If you want a decimal period, independent of the user's locale, then add

fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX")

Swift 3:

let fmt = NumberFormatter()
// Optional:
fmt.locale = Locale(identifier: "en_US_POSIX")

fmt.minimumIntegerDigits = 1
fmt.maximumFractionDigits = 4
fmt.minimumFractionDigits = 0

print(fmt.string(from: 25.0 / 10.0 as NSNumber)!)  // 2,5
print(fmt.string(from: 20.0 / 10.0 as NSNumber)!)  // 2
print(fmt.string(from: 2.0 / 7.0 as NSNumber)!)    // 0,2857


回答5:

Working on a calculator on Swift 4, I treated the number variables as String so I could display them on screen and converted them to Double for the calculations, then convert them back to String to display the result. When the result was an Int I didn't want the .0 to be displayed as well so I worked this out and it was pretty simple

    if result.truncatingRemainder(dividingBy: 1) == 0{
    screenLabel.text = String(Int(result))
    }
    else{
    screenLabel.text = String(result)
    }

so result is the variable in Double format, if divided by 1 it gives us 0 (perfect division means its an Int), I convert it in Int.