从`NSDecimal`或`NSDecimalNumber`转换为C#的`decimal`类型 [英] Converting from `NSDecimal` or `NSDecimalNumber` to C#'s `decimal` type

查看:128
本文介绍了从`NSDecimal`或`NSDecimalNumber`转换为C#的`decimal`类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从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:

  1. 假设我了解每种格式的二进制实现并进行自己的按位转换,或者
  2. NSDecimalNumber给我一个字符串,然后让decimal解析它.
  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.

我认为选项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.

推荐答案

仅因为这使我绊倒了,并花费了我不少时间,所以这里有一些扩展方法,我现在在NSDecimaldecimal之间进行转换.这真令人沮丧,令我惊讶的是,没有更好的内置方法.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆