从`NSDecimal`或`NSDecimalNumber`转换为C#的`decimal`类型 [英] Converting from `NSDecimal` or `NSDecimalNumber` to C#'s `decimal` type
问题描述
我从StoreKit的SKProduct
类中得到了一个NSDecimalNumber
,我想将其转换为C#的decimal
类型,以最大程度地减少精度损失.有没有一种简单的方法可以做到这一点?
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:
- 假设我了解每种格式的二进制实现并进行自己的按位转换,或者
- 让
NSDecimalNumber
给我一个字符串,然后让decimal
解析它.
- Assume that I understand the binary implementation of each and do my own bit-wise conversion, or
- Have
NSDecimalNumber
give me a string and then havedecimal
parse it.
我认为选项1的工作量太大,甚至可能很脆弱,因此我倾向于选择选项2.但这似乎也不是我能做的最好的选择. (我可以忍受它会多么慢,因为它很少发生.
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.
推荐答案
仅因为这使我绊倒了,并花费了我不少时间,所以这里有一些扩展方法,我现在在NSDecimal
和decimal
之间进行转换.这真令人沮丧,令我惊讶的是,没有更好的内置方法.
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;
}
}
这篇关于从`NSDecimal`或`NSDecimalNumber`转换为C#的`decimal`类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!