Converting from `NSDecimal` or `NSDecimalNumber` t

2019-07-01 13:54发布

问题:

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.

回答1:

Just because this tripped me up and cost me quite some time here's a couple extension methods I now use for conversion between NSDecimal and decimal. This was quite frustrating and I am surprised there is no better way built in.

public static class NumberHelper
{
    public static decimal ToDecimal(this NSDecimal number)
    {
        var stringRepresentation = new NSDecimalNumber (number).ToString ();
        return decimal.Parse(stringRepresentation, CultureInfo.InvariantCulture);
    }

    public static NSDecimal ToNSDecimal(this decimal number)
    {
        return new NSDecimalNumber(number.ToString(CultureInfo.InvariantCulture)).NSDecimalValue;
    }
}


回答2:

NSDecimal and NSDecimalNumber structures representation are not identical to .NET System.Decimal.

Conversion is always possible but not easy. If performance is not a huge matter then you'll best served by using the string representation to convert between them.