Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDecimalRound in Swift

Tags:

macos

ios

swift

Trying to figure out the 'correct' way to round down decimal numbers in Swift and struggling to set up the C calls correctly (or something) as it is returning a weird result. Here's a snippet from 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)")

Output -> From: 1.54762, to: 1.54761981964356

I was hoping for 1.54. Any pointers would be appreciated.

like image 939
samnovotny Avatar asked Dec 05 '25 14:12

samnovotny


1 Answers

The rounding process should be pretty straightforward without any wrappers. All we should do -- just call the function NSDecimalRound(_:_:_:_:), described there: 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
like image 176
Ruben Kazumov Avatar answered Dec 07 '25 04:12

Ruben Kazumov