打印Double为Int - 如果不是Double值 [英] Print Double as Int - if not a Double value
本文介绍了打印Double为Int - 如果不是Double值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例;
我希望我的Double显示为Int,如果该值是一个整数,
var Value = Double()
。
Value = 25.0 / 10.0
现在我想要值
显示 2.5
(插入标签时)
。
值= 20.0 / 10.0
p>
现在我想要值
显示 2
- 而不 2.0
解决方案
一种经典的方式是建立一个代表epsilon的值你的容忍度考虑一个值足够接近一个 Int
:
/近距离足够被认为是Int?
let kEPSILON = 0.0001
var val = 1.9999
var str:String
如果abs(val - round(val))< kEPSILON {
str = String(Int(round(val)))
} else {
str = String(val)
}
print str)//2
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
解决方案
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"
这篇关于打印Double为Int - 如果不是Double值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文