在NSDecimalNumber的索引处查找数字
问题描述:
是否可以在NSDecimalNumber的索引处找到数字?在NSDecimalNumber的索引处查找数字
例如是这样的可能吗?
var a: NSDecimalNumber = 10.0
var indexOfa = a(index: 6)
//indexOfa = 6 (6th position from the left)
基本上,我试图让这轮下来x.xx5和x.xx6围捕自定义舍入函数。
例如: 67.5558被四舍五入为67.55。 67.5568四舍五入为67.56。
...不是四舍五入问题的重复。我在此特别要求如何在NSDecimalNumber的指定索引处查找数字。
此外,您链接的答案不能回答我的问题。我可以使用NSDecimalNumber的四舍五入行为,但是它会向上取整.5我需要它在.5和.6之间舍入。如果我能找到第二个十进制数的索引,我可以创建自己的自定义舍入函数。
我有一个可行的解决方案。但它很可怕。这里有一些NSDecimalNumber扩展,但你可以猜测他们在做什么。我敢肯定,那里有一个更好的办法...
public func currencyRoundDown() -> NSDecimalNumber {
let rounded: NSDecimalNumber
let toThree = self.roundDown(3)
let lower = self.roundDown(2).adding(0.005)
if lower.moreThan(toThree) || lower.same(toThree) {
rounded = toThree.roundDown(2)
} else {
rounded = toThree.roundUp(2)
}
return rounded
}
答
是否有可能找到一个NSDecimalNumber的指数是多少?
让我们来考虑如何用Double来做到这一点。在这个渲染中,“索引”从小数点开始计数。
将索引乘以10,使索引数字进入1位。现在取模10的余数。这是有问题的数字。
let d = 1234.56789 // the 5 is 1, the 6 is 2, the 7 is 3 ...
let place = 3
let shift = pow(10.0, Double(place)) * d
let digit = Int(shift) % 10 // 7
你可以研究了它,请看看这个问题 - > https://*.com/questions/41744278/count-number-of-decimal-places-in-a-float-or-decimal -in-swift –
@LateNate不要复制你自己的问题。如果你问这个问题有什么问题,请编辑它。 – matt
我不同意它不回答你的问题。如果你想到https://*.com/questions/27338573/rounding-a-double-value-to-x-number-of-decimal-places-in-swift的答案,你可以看到答案是_is_ there 。问题是,你的问题并没有增加混合;你可以通过搜索(并思考)来了解这一点。 – matt