从`NSDecimal`或`NSDecimalNumber`转换为C#的`decimal`类型
我从StoreKit的SKProduct
类得到了一个NSDecimalNumber
,我想将它转换为C#的decimal
类型,以最大限度地减少精度损失。 有没有直接的方法来做这样的事情?
我认为我的两个选择是:
- 假设我理解每个的二进制实现并执行我自己的逐位转换,或者
- 让
NSDecimalNumber
给我一个字符串,然后有decimal
解析它。
我认为选项1是太多的工作,甚至可能是脆弱的,所以我倾向于使用选项2.但这似乎不是我能做的最好的。 (我可以忍受它的速度有多慢,因为它极少发生。
只是因为这使我绊倒并花了我相当长的时间这里有一些扩展方法,我现在用于NSDecimal
和decimal
之间的转换。 这非常令人沮丧,我很惊讶没有更好的内置方式。
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; } }
NSDecimal
和NSDecimalNumber
结构表示与.NET System.Decimal
。
转换总是可行但不容易。 如果性能不是一个大问题,那么最好通过使用string
表示在它们之间进行转换。