[英]Using iOS NumberFormatter to format decimal into fraction representation
In iOS, how can use NumberFormatter to format the decimal part of a number into its fractional representations.在 iOS 中,如何使用 NumberFormatter 将数字的小数部分格式化为其小数表示。
For example I would like to format the number 2.375
as 2 3/8
.例如,我想将数字2.375
格式化为2 3/8
。
Can this be done with NumberFormatter?这可以用 NumberFormatter 完成吗?
No. You would need to implement your own Rational Formatter.不,您需要实现自己的 Rational Formatter。 You can use this answer from Martin R as a starting point.您可以使用 Martin R 的这个答案作为起点。 You can do something like:您可以执行以下操作:
class RationalFormatter: Formatter {
let precision: Double = 1.0E-6
override public func string(for obj: Any?) -> String? {
guard let value = obj as? Double else { return nil }
let whole = modf(value).0
var x = modf(value).1
var a = x.rounded(.down)
var (h1, k1, numerator, denominator) = (1, 0, Int(a), 1)
while x - a > precision * Double(denominator) * Double(denominator) {
x = 1.0/(x - a)
a = x.rounded(.down)
(h1, k1, numerator, denominator) = (numerator, denominator, h1 + Int(a) * numerator, k1 + Int(a) * denominator)
}
var string = ""
if whole < 0 || numerator < 0 {
string += "-"
}
if whole != 0 {
string += String(Int(abs(whole)))
}
if whole != 0 && numerator != 0 {
string += " "
}
if numerator != 0 {
string += "\(abs(numerator))/\(abs(denominator))"
}
return string
}
}
Usage:用法:
let double = 2.375
let rationalFormatter = RationalFormatter()
let formatted = rationalFormatter.string(for: double) // "2 3/8"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.