gpt4 book ai didi

ios - Swift 中的 NSDecimalRound

转载 作者:行者123 更新时间:2023-11-28 05:30:47 30 4
gpt4 key购买 nike

试图找出在 Swift 中舍入小数的“正确”方法,并努力正确设置 C 调用(或其他),因为它返回了一个奇怪的结果。这是 Playground 的一个片段:

import Foundation

func roundTo2(result: UnsafePointer<Double>, number: UnsafePointer<Double>) {

var resultCOP = COpaquePointer(result)
var numberCOP = COpaquePointer(number)

NSDecimalRound(resultCOP, numberCOP, 2, .RoundDown)

}

var from: Double = 1.54762
var to: Double = 0.0

roundTo2(&to, &from)

println("From: \(from), to: \(to)")

输出 -> 从:1.54762,到:1.54761981964356

我希望是 1.54。任何指针将不胜感激。

最佳答案

舍入过程应该非常简单,无需任何包装器。我们应该做的就是调用函数 NSDecimalRound(_:_:_:_:),那里有描述:https://developer.apple.com/documentation/foundation/1412204-nsdecimalround

import Cocoa

/// For example let's take any value with multiple decimals like this:
var amount: NSDecimalNumber = NSDecimalNumber(value: 453.585879834)

/// The mutable pointer reserves only "one cell" in memory for the
let uMPtr = UnsafeMutablePointer<Decimal>.allocate(capacity: 1)

/// Connect the pointer to the value of amount
uMPtr[0] = amount.decimalValue

/// Let's check the connection between variable/pointee and the poiner
Swift.print(uMPtr.pointee) /// result: 453.5858798339999232

/// One more pointer to the pointer
let uPtr = UnsafePointer<Decimal>.init(uMPtr)

/// Standard function call
NSDecimalRound(uMPtr, uPtr, Int(2), NSDecimalNumber.RoundingMode.bankers)

/// Check the result
Swift.print(uMPtr.pointee as NSDecimalNumber) /// result: 453.59

关于ios - Swift 中的 NSDecimalRound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28651848/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com