查找小数中第 n 位的数字的最佳方法是什么?
背景
我正在研究一个对称舍入类,我发现我陷入了如何最好地找到我将要舍入的位置 x 处的数字的困境。我确信有一种有效的数学方法可以找到单个数字并返回它,而无需诉诸字符串解析。
问题
假设我有以下 (C#) 伪代码:
var position = 3;
var value = 102.43587m;
// I want this no ↑ (that is 5)
protected static int FindNDigit(decimal value, int position)
{
// This snippet is what I am searching for
}
另外,值得注意的是,如果我的值是整数,我将需要为 FindNDigit 的结果返回零。
有人对我应该如何解决这个问题有任何提示吗?这是我错过的明显的东西吗?
Background
I'm working on a symmetric rounding class and I find that I'm stuck with regards to how to best find the number at position x that I will be rounding. I'm sure there is an efficient mathematical way to find the single digit and return it without having to resort to string parsing.
Problem
Suppose, I have the following (C#) psuedo-code:
var position = 3;
var value = 102.43587m;
// I want this no ↑ (that is 5)
protected static int FindNDigit(decimal value, int position)
{
// This snippet is what I am searching for
}
Also, it is worth noting that if my value is a whole number, I will need to return a zero for the result of FindNDigit.
Does anyone have any hints on how I should approach this problem? Is this something that is blaringly obvious that I'm missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
以前的解决方案都不适合我,所以这里是一个有效的解决方案:
var result = value / Math.Pow(10, Math.Truncate((Math.Log10(value) + 1) -position));
返回(int)(结果%10);
None of the previous solutions worked for me, so here is a working one :
var result = value / Math.Pow(10, Math.Truncate((Math.Log10(value) + 1) - position));
return (int)(result % 10);
怎么样:
基本上,您乘以
10 ^ pos
以便将该数字移动到 1 的位置,然后使用模运算符%
来除以其余部分数字。How about:
Basically you multiply by
10 ^ pos
in order to move that digit to the one's place, and then you use the modulus operator%
to divide out the rest of the number.编辑:
如果您愿意,您可以将递归调用与初始调用分开,以删除递归期间的初始条件检查:
以下是一些测试:
Edit:
If you wish, you may separate the recursive call from the initial call, to remove the initial conditional checks during recursion:
Here's a few tests:
编辑:这里完全有错误和相反的答案。我正在计算小数点左侧而不是右侧的位置。请参阅正确的代码的赞成答案。
Edited: Totally had the wrong and opposite answer here. I was calculating the position to the left of the decimal instead of the right. See the upvoted answers for the correct code.
我找到了这个
还有这个知道完整值(即:111,位置3 = 100,抱歉我不知道正确的名称):
I found this one here working:
And also this one to know the full value (i.e.: 111, position 3 = 100 , sorry I don't know the proper name):
这个怎么样:
How about this: