converting to double to two decimal places
Solution 1
Use Math.Round
Math.Round(mydoublevalue, 2);
In your code
tbtotal2.Text = Math.Round(total2, 2).ToString();
Solution 2
My answer is pretty late but for those out there like me who want:
to convert to double/decimal and also want the value to always show 2 decimal places (.00) as String
tbtotal2.Text = Math.Round(total2, 2).ToString("#.00");
The below means two decimal places at all times.
"#.00"
The below means two decimal places if there is value.
"#.##"
Solution 3
If you only want the value rounded for display as a string, you can also use String.Format.
tbtotal1.Text = String.Format("{0:0.##}", total1);
The text "{0:0.##}" describes how you want it to be formatted. The # indicates that ending zeroes should not be included (eg 1.2 stays the string "1.2"), if you instead do "{0:0.00}", two decimal places are included no matter what, so the double 1.2 would become "1.20".
Solution 4
Do it like this.
tbtotal1.Text = Math.Round(double.Parse(total1.ToString()), 2).ToString();
tbtotal2.Text = Math.Round(double.Parse(total2.ToString()), 2).ToString();
user1483145
Updated on July 05, 2022Comments
-
user1483145 almost 2 years
Hi i am a c# novice would someone politely tell me how to convert the values of this piece of code to a double/rounded decimal.. thanks in advance
DataTable dtValues = new DataTable("GetValues"); strValueNumber = ValueNumber[0].ToString(); dtGetValues = SQLMethods.GetValues(strValueNumber); total = 0; for (int i = 0; i < dtValues.Rows.Count; i++) { total1 = total1 + Convert.ToInt32(dtGetValues.Rows[i]["total_1"]); total2 = total2 + Convert.ToDouble(dtGetValues.Rows[i]["total_2l"]) * .45; tbtotal1.Text = total1.ToString(); tbtotal2.Text = total2.ToString(); } } catch (Exception ex) { MessageBox.Show("Error in returning selected Values. " + "Processed with error:" + ex.Message); } }