当已知位置数时,按 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/