.net - 按 10 的幂缩放十进制值

标签 .net decimal

当已知位置数时,按 10 的幂缩放 System.Decimal 值的最佳方法是什么?
value * (decimal)Math.Pow(10, places)想到,但它有两个缺点:

  • 它引入了浮点数,这使得随着数字变大而难以推断舍入错误。
  • 当您尝试做的只是更改已在十进制数据结构中编码的简单比例组件时,进行求幂似乎有些过分。

  • 有没有更好的方法?

    最佳答案

    您可以创建一个 10 的幂表,例如:

    var pow10s = new int [] { 1, 10, 100, 1000, 10000, 100000, ... };
    

    然后使用地点作为该表的索引:
    return value * pow10s[place]
    

    更新:
    如果您不希望在尝试将数组索引到 N 个位置后发生崩溃,则可以采用稍微复杂的方法,如下所示:
    public class Power10Scale
    {
        private static readonly int[] Pow10s = {
            1, 10, 100, 1000, 10000, 100000,
        };
    
        public static int Up(int value, int places)
        {
            return Scale(value, places, (x, y) => x * y);
        }
    
        public static int Down(int value, int places)
        {
            return Scale(value, places, (x, y) => x / y);
        }
    
        private static int Scale(int value, int places, Func<int, int, int> operation)
        {
            if (places < Pow10s.Length)
                return operation(value, Pow10s[places]);
    
            return Scale(
                operation(value, Pow10s[Pow10s.Length - 1]),
                places - (Pow10s.Length - 1),
                operation);
        }
    }
    

    关于.net - 按 10 的幂缩放十进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43745549/

    相关文章:

    c# - WebClient 类的域凭据不起作用

    c# - 如何从不同的类注册鼠标事件

    C# XML 序列化和十进制值

    c# - mysql 不接受正确格式的小数

    .net - 从数据库读取十进制值时出现 OverflowException

    从整个列中的字符串中替换小数点

    Java Double 始终四舍五入为小数点后两位

    c# - 如何在单元测试中调用公共(public)静态方法

    .net - 如何为多个解决方案配置 TeamCity Inspections (.NET) Runner

    .net - 在 IIS6 中使用免费 SSL 证书设置测试 asp.net 站点的详细步骤是什么?