Newbie - need to round field to 2 decimal places

rm103
rm103 used Ask the Experts™
on
Hello all:

Newbie trying to creating labels and trying to round field to 2 decimals. the below line yields the following result:

Output = this["QTY_TOPICK"].ToString();

When I print the label I get "60.00000". I need to reduce it to "60.00" and am unsure of how code this. I believe this is c#.

When you have a chance please advise.

Thanks,

Rm103
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Ryan ChongSoftware Team Lead

Commented:
try:
Output = this["QTY_TOPICK"].ToString("#,0.00");

Open in new window

Author

Commented:
didn't work. I got the following error:

Cannot convert from 'string' to IE to 'System.IFormatProvider'
Commented:
So you need to convert to a Decimal first then you can provide the ToString with the format; e.g. -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;

namespace EE_Q28744239
{
	class Program
	{
		static readonly List<Order> orders = new List<Order>();

		static void Main(string[] args)
		{
			orders.AddRange((from i in Enumerable.Range(0, 10) select new Order() { ID = i, Name = string.Format("Order{0}", i), Quantity = ((i + 5) * 2) }));
			DataTable table = orders.ConvertToDataTable();

			for (int i = 0; i < table.Rows.Count; i++)
				Console.WriteLine("Quantity for {0} is: {1}", table.Rows[i]["Name"], Convert.ToDecimal(table.Rows[i]["Quantity"]).ToString("N2"));
			Console.ReadLine();
		}
	}

	class Order
	{
		public int ID { get; set; }
		public string Name { get; set; }
		public int Quantity { get; set; }
	}

	static class Extensions
	{
		public static DataTable ConvertToDataTable<T>(this IEnumerable<T> source)
		{
			var properties = TypeDescriptor.GetProperties(typeof(T));
			var table = new DataTable();
			foreach (PropertyDescriptor property in properties)
				table.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);

			foreach (T item in source)
			{
				DataRow row = table.NewRow();
				foreach (PropertyDescriptor property in properties)
					row[property.Name] = property.GetValue(item) ?? DBNull.Value;
				table.Rows.Add(row);
			}
			return table;
		}
	}
}

Open in new window

Which produces the following output -Capture.JPG
It should be noted that, the ToString method would also accept:
// Provides the same output as using N2
Convert.ToDecimal(table.Rows[i]["Quantity"]).ToString("0.00")

Open in new window

-saige-

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial