转换十进制到尽可能小的数字类型,没有任何数据丢失没有任何、数据丢失、类型、数字

2023-09-06 22:05:39 作者:小喵

我想写一个它把一个十进制到尽可能小的数值类型没有任何数据丢失的方法。对于例子:

转换(1)应该返回一个字节 转换(257)应该返回一个 转换(1.1)应该返回一个浮动

该方法的输入始终是一个十进制,输出为以下任何.NET数字类型:为sbyte 字节 USHORT INT UINT ULONG 浮动十进制

我用试过()检查发生OverflowException ,但是这种做法并不prevent损失。例如,检查((INT)1.1)不会引发任何异常并返回 1 !因此,这不是我想要的。

任何建议?

更新:料方法签名

 公共对象转换(十进制D)
{
   // 返回 ...
}
 

解决方案

您可以尝试使用的TryParse

 短水库;
        十进制值= 8913798132;
        布尔S = short.TryParse(value.ToString(),从水库); //返回false
 
Java二进制 数据类型 浮点数 运算符 分隔符 转义字符 注释

I want to write a method which converts a decimal to the smallest possible numeric type without any data loss. For examples:

Convert(1) should return a byte Convert(257) should return a short Convert(1.1) should return a float and so on

The input of the method is always a decimal and the output is any of the following .NET numeric types: sbyte, byte, short, ushort, int, uint, long, ulong, float, double, and decimal.

I have tried using checked() to catch the OverflowException, however that approach doesn't prevent loss. For example, checked((int)1.1) won't throw any exception and return 1! Therefore, it's not what I want.

Any recommendation?

Update: expected method signature

public object Convert(decimal d)
{
   // return ...
}

解决方案

you can try to use TryParse

        short res;
        decimal value = 8913798132;
        bool s = short.TryParse(value.ToString(), out res); // returns false

 
精彩推荐
图片推荐