Search code examples
c#xamarin.iostype-conversiondecimalnsdecimalnumber

Converting from `NSDecimal` or `NSDecimalNumber` to C#'s `decimal` type


I've got an NSDecimalNumber from StoreKit's SKProduct class, and I want to convert it to C#'s decimal type to minimize loss of precision. Is there a straightforward way to do such a thing?

I figure my two choices are:

  1. Assume that I understand the binary implementation of each and do my own bit-wise conversion, or
  2. Have NSDecimalNumber give me a string and then have decimal parse it.

I figure option 1 is way too much work and probably even brittle, so I'm inclined to go with option 2. But that doesn't seem like the best I can do, either. (I can live with how slow it'll be, because it happens exceptionally rarely.


Solution

  • Since Xamarin iOS SDK 12, operators are available for explicitly converting an NSDecimal to a decimal and implicitly converting a decimal to an NSDecimal.

    Using these operators, you can take the following code as an example for achieving your goal:

    var nsDecimalNumber = new NSDecimalNumber("128.478", new NSLocale("en-US"));
    var nsDecimal = nsDecimalNumber.NSDecimalValue;
    var csharpDecimal = (decimal)nsDecimal;
    var nsDecimalAfterConversion = (NSDecimal)csharpDecimal;
    var nsDecimalNumberAfterConversion = new NSDecimalNumber(nsDecimalAfterConversion);