【问题标题】:Formatting decimal xamarin格式化十进制 xamarin
【发布时间】:2018-06-08 13:14:23
【问题描述】:

我是 c# 的新手,我找不到格式化数字的方法。我只想显示小数点后两位。

namespace Dolar
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void Button_Clicked(object sender, EventArgs e)
        {
            XmlDocument doc1 = new XmlDocument();
            doc1.Load("http://www.tcmb.gov.tr/kurlar/today.xml");
            XmlElement root = doc1.DocumentElement;
            XmlNodeList nodes = root.SelectNodes("Currency");

            foreach (XmlNode node in nodes)
            {
                var attributeKod = node.Attributes["Kod"].Value;
                if (attributeKod.Equals("USD"))
                {
                    var a = node.SelectNodes("BanknoteSelling")[0].InnerText;
                    var b = node.SelectNodes("BanknoteBuying")[0].InnerText;
                    float c = float.Parse(a);
                    float d = float.Parse(b);                 
                    label2.Text = a;
                    label3.Text = b;


                }

                var attributeKod1 = node.Attributes["Kod"].Value;
                if(attributeKod1.Equals("EUR"))
                {
                    var a = node.SelectNodes("BanknoteSelling")[0].InnerText;
                    var b = node.SelectNodes("BanknoteBuying")[0].InnerText;
                    float c = float.Parse(a);
                    float d = float.Parse(b);
                    label4.Text = a;
                    label5.Text = b;
                }
                }
            }
    }
}

输出是;

4.5173 //4.51
4.4992 //4.49
5.3131 //5.31
5.2919 //5.29

【问题讨论】:

    标签: c# xamarin.forms decimalformat


    【解决方案1】:

    你可以像这样格式化它们:

    String.Format("{0:0.00}", 4.5173);    output will be  // "4.51"
    

    或: 通过使用数学类:

    float value = 4.5173;
    value = System.Math.Round(value,2);
    

    【讨论】:

      【解决方案2】:

      请注意,您没有将已解析的 float 变量(c 和 d)分配给文本框。您可以使用格式说明符“0.00”,如下所示:

      var c = float.Parse(a);
      var d = float.Parse(b);
      label4.Text = c.ToString("0.00");
      label5.Text = d.ToString("0.00");
      

      您还混合了隐式类型的var 变量和显式类型的变量(例如float c)。我建议坚持var

      【讨论】:

        【解决方案3】:

        我会使用内置格式。

        在您的情况下,它是 i.ToString("F2") 甚至是 i.ToString("F2", CultureInfo.InvariantCulture) 。

        2 表示两位小数,F 表示定点格式。

        查看来源:https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#FFormatString

        但是,您应该对此进行测试,因为我不确定这对于 Xamarin 是否正确。它适用于 .Net。

        【讨论】:

          猜你喜欢
          • 2013-08-22
          • 1970-01-01
          • 2020-07-21
          • 1970-01-01
          • 2013-07-29
          • 2011-09-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多