3

I am new to c# and I couldn't find a way to format my numbers. I want to show only 2 digits after decimal.

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; } } } } } 

outputs are;

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

3 Answers 3

3

you can format them like this :

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

or : by using Math class :

float value = 4.5173; value = System.Math.Round(value,2); 
Sign up to request clarification or add additional context in comments.

Comments

2

Note that you aren't assigning your parsed float variables (c and d) to the textboxes. You can use the format specifier "0.00", like so:

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

You've also mixed implicit typed var variables and explicitly typed variables (e.g. float c). I would suggest sticking to var

Comments

0

I would use the built in formats.

In your case it's i.ToString("F2") or even i.ToString("F2", CultureInfo.InvariantCulture) .

The 2 signifies 2 decimal places, and the F signifies the Fixed-Point Format.

See source: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#FFormatString

You should test this, however, as I'm not sure this is correct for Xamarin. It's for .Net.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.