我从StoreKit的NSDecimalNumber
类获得SKProduct
,我想将其转换为C#的decimal
类型,以最大限度地减少精度损失。有没有直接的方法来做这样的事情?
我认为我的两个选择是:
NSDecimalNumber
给我一个字符串,然后让decimal
解析它。我认为选项1工作太多,甚至可能很脆弱,所以我倾向于使用选项2.但这似乎不是我能做的最好的。 (我可以忍受它的速度有多慢,因为它极少发生。
答案 0 :(得分:3)
NSDecimal
和NSDecimalNumber
结构表示与.NET System.Decimal
不同。
转换总是可行但不容易。如果性能不是一件大事,那么最好使用string
表示在它们之间进行转换。
答案 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;
}
}
答案 2 :(得分:1)
自 Xamarin iOS SDK 12 起,运算符可用于 explicitly converting an NSDecimal to a decimal 和 implicitly converting a decimal to an NSDecimal。
使用这些运算符,您可以将以下代码作为实现目标的示例:
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);