【问题标题】:How to get selected number after decimal point如何在小数点后获得选定的数字
【发布时间】:2015-09-15 13:45:58
【问题描述】:

我对 Example 有一个 double 值

0.0070
0.100
0.040

我想输出上述数字如下

70
100
40

请指导我 谢谢

【问题讨论】:

  • 为什么是 70,而不是 7(或 700?)
  • 您需要尾随零吗?我看不出这怎么可能……
  • 你的问题是错误的,而且 StackOverflow 不是一个代码编写服务。展示您迄今为止的尝试,我们或许可以提供帮助。

标签: c# .net


【解决方案1】:

理论上是这样的

double number = 0.0070
string num = number.ToString();           //Convert to string
int index = num.IndexOf('.') + 1;         //Find the decimal
string trunc = num.Substring(index);      //Get rid of everything before it
trunc.TrimStart('0');                     //Get rid of leading zeros
double result = Convert.ToDouble(trunc);  //Convert back to double

但是,C# 不尊重数值中的尾随零,因此只要您将 0.0070 转换为双精度,它就会被截断为 0.007

【讨论】:

  • 这会给你70 - 不,不会。
  • 说出答案有什么问题或提出修改建议比仅仅说错误更有帮助。有建设性
  • 正如 Rowland Shaw 和 Michael McMullin 所说 - 鉴于当前的问题描述,这是不可能的。
  • 您是正确的,因为 C# 不尊重数值中的尾随零。我忘了。但是,在您引用的任何一个 cmets 中都没有说明这一点,您可以在我帖子的第一条评论中简单地说明这一点。
  • 但是您发布了代码。您不尝试在发布之前执行它吗?如果原始值作为字符串而不是双精度给出,则可以解决问题的唯一方法。
【解决方案2】:
public int getTheNumberAfterDecimalPoint(double number)
{
    string numberInString = Convert.ToString(number);
    if(numberInString.Contains('.'))
    {
        return Convert.ToInt32(numberInString.Substring('.')[1]);
    }
    return Convert.ToInt32(number);
}

【讨论】:

    猜你喜欢
    • 2011-04-22
    • 1970-01-01
    • 2011-09-04
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多