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

狂风中的少年 提交于 2019-12-10 18:49:27

问题


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.



来源:https://stackoverflow.com/questions/11731721/converting-from-nsdecimal-or-nsdecimalnumber-to-cs-decimal-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!