问题描述
我正面临一种情况,在这种情况下,我只需要在float的小数点后保留2位,而无需舍入其实际值.
I am facing one scenario where I need only 2 places after the decimal point of float without rounding its actual value.
我尝试了以下代码行:
extension Float {
func stringWith2Decimals() -> String {
return String(format: "%.2f", self)
}
}
这给了我以下输出:
var floatValue = 10.99999999
预期结果:10.99
Expected result: 10.99
请让我知道您的想法.
推荐答案
经过测试,这将为您提供帮助.
This will help you, I have tested it.
let floatValue = 10.99999999
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.roundingMode = .down
let s = formatter.string(from: NSNumber(value: floatValue))
print(s)
更新的答案为 还有一个案例,其值为10.9,应显示10.90.
Updated answer for one more case is there for value 10.9 it should show 10.90.
情况1:当您只想打印实际的十进制数字或最多2个十进制数字
Case 1: When you only want to print actual decimal digits or max 2 decimal digit
let floatValue = 10.999999
let floatValue1 = 10
let floatValue2 = 10.9
let floatValue3 = 10.91
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 2
formatter.roundingMode = .down
let s = formatter.string(from: NSNumber(value: floatValue))
print(s!) // 10.99
let s1 = formatter.string(from: NSNumber(value: floatValue1))
print(s1!) // 10
let s2 = formatter.string(from: NSNumber(value: floatValue2))
print(s2!) // 10.9
let s3 = formatter.string(from: NSNumber(value: floatValue3))
print(s3!) // 10.91
情况2:当您始终要打印两位十进制数字时.
Case 2: When you always want to print two decimal digits.
let floatValue = 10.999999
let floatValue1 = 10
let floatValue2 = 10.9
let floatValue3 = 10.91
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
formatter.roundingMode = .down
let s = formatter.string(from: NSNumber(value: floatValue))
print(s!) // 10.99
let s1 = formatter.string(from: NSNumber(value: floatValue1))
print(s1!) // 10.00
let s2 = formatter.string(from: NSNumber(value: floatValue2))
print(s2!) // 10.90
let s3 = formatter.string(from: NSNumber(value: floatValue3))
print(s3!) // 10.91
希望您得到想要的东西.如果是,那么请投票,否则让我知道您的实际要求.
Hope you get what you want. if yes then please vote up else let me know what is your actual requirement.
问题的更新答案. 对于诸如10.9999999999999999之类的值,其打印为11.00,而不是10.99.
Updated answer for an issue . for value like 10.9999999999999999 its printing 11.00, Not 10.99.
let floatValue3 = 10.99999999999999
let (wholePart, fractionalPart) = modf(floatValue3)
let stringFractionalPart = "\(fractionalPart)"
let stringWholePart = "\(Int(wholePart))"
let aryFractionalPart = stringFractionalPart.components(separatedBy: ".")
var valueToDisplay = stringWholePart
if aryFractionalPart.count >= 2 {
let decimalDigits = aryFractionalPart[1]
let digit2 = decimalDigits.prefix(2)
valueToDisplay = "\(valueToDisplay).\(digit2)"
}
print(valueToDisplay)
希望我现在能满足您的要求.
Hope now I fulfill your requirement.
这篇关于从float获取字符串而不舍入其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!