【问题标题】:Deduce all characters behind decimal number, with leading 0's推导十进制数后面的所有字符,前导 0
【发布时间】:2018-08-08 02:16:05
【问题描述】:

如果我有一个输入字符串,input 有三个或更多小数我希望该字符串由单独的if-loop 处理。

为此,我创建了以下控制台程序,如果(第一个约束)有小数点,则输入if-loop,字符串中有.,(第二个约束)如果小数为三或更多。

using System;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "0.065";
            string output;

            Console.WriteLine(input.ToString());  // (1)
            Console.WriteLine(input.ToString().IndexOf("."));  // (2)
            Console.WriteLine(input.ToString().Substring(input.ToString().IndexOf("."))); // (3)

            if (Convert.ToInt32(input.IndexOf('.')) != -1 && 
            Convert.ToInt32(input.Substring(input.IndexOf('.') + 1).Length) >= 3)
            {
                output = input.Substring(input.IndexOf('.') + 1);
                Console.WriteLine(Convert.ToInt32(output));
            }
                Console.ReadLine();
        }
    }
}

这会产生预期的结果,即

(1) 打印0.065

(2) 打印1

(3) 打印.065

和 (4) 打印 3

我的问题是,当我删除硬编码字符串值时,input = "0.065" 并将其替换为

input = Row["Price"].ToString();

其中Row["Price"].ToString(); 是来自 XML 文件的值,它也具有值 0.065 我从控制台得到以下打印:

(1) 产生0.065

(2) 产生 -1(应该为 1,因为存在 .

(3) 产生0.065(应该是.065

并且 (4) 没有被打印,因为 if constraints 不满足。

有人知道这是为什么吗?我是 C# 新手,但我认为由于 input 在这两种情况下都是 string 类型,应该没有什么区别吗?特别是当我将ToString() 应用于我的新string input 时?

【问题讨论】:

  • Row["Price"].ToString(); is a value from a XML file 看起来肯定不像从 XML 中读取的内容。您能否在其中包含您正在读取该值的代码以及Row 是什么?
  • 你确定没有 ,而不是 .在那个字符串中然后你input = Row["Price"].ToString();
  • 这只是意味着您的输入不包含“。”性格,即使你认为是这样。也许它包含逗号而不是点,或者其他东西 - 我们无法弄清楚。只要做Console.WriteLine(Row["Price"].ToString()) 看看你自己。
  • 可能是您的行["Price"] 包含一个数值,其中 "," 作为分隔符,而不是 "."
  • @k.Lennartz 我打印了input,但没有看到,,而是.。但是当我做input = Row["Price"].ToString().Replace(",",".") 时它起作用了,所以一定是因为它们看起来非常相似(我的真实打印使用一个以粗体打印的函数,所以,. 之间的区别更加微妙。三个人建议这样做,但既然你是第一个,我相信如果你写你的评论作为答案我会接受它是正确的。

标签: c# string output


【解决方案1】:

当您执行input = Row["Price"].ToString(); 时,将, 替换为该字符串中的.

替换函数为input = Row["Price"].ToString().Replace(",", ".");

【讨论】:

    猜你喜欢
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 2017-09-09
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2019-06-12
    相关资源
    最近更新 更多