Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a formula below to calculate a column from a datagridview.
How to round with Math.Round (val, 2)

C#
int i;
int NbLig = DGV_P9_Commande.Rows.Count;
Double Val = 0;
for (i = 0; i < NbLig; i++)
{
    Val += Convert.ToDouble(DGV_P9_Commande.Rows[i].Cells[5].Value);

}

Txt_total_P9_cmd.Text = Convert.ToString(Val) + "  €uros H.T";


My result does not work ....

thank you

What I have tried:

Txt_total_P9_cmd.Text = Math.Round((Convert.ToString(Val)), 2) + " €uros H.T";
Posted
Updated 17-Jan-20 6:04am
Comments
ZurdoDev 17-Jan-20 11:06am    
How does it not work?
OriginalGriff 17-Jan-20 11:09am    
"It's not working" is one of the most useless problem descriptions we get: it tells us absolutely nothing about the problem. We don't know if you get an error message, or the wrong data, or even that that code compiles successfully!
Remember that we can't see your screen, access your HDD, or read your mind - we only get exactly what you type to work with.
So tell us what happens when you run that code, what you expected to happen, how you checked what happened. Help us to help you!
Use the "Improve question" widget to edit your question and provide better information.
Richard Deeming 17-Jan-20 11:44am    
It doesn't work because you're converting the number to a string before you attempt to round it.

You can't round a string; you can only round a number.

You need to round the value before you convert it to a string. Phil's answer shows you how.

C#
Txt_total_P9_cmd.Text = string.Format
(
   "{0} €uros H.T.",
   Math.Round(Val, 2)
); 

Edit: if it is only a matter of displaying two decimal digits, then:
C#
Txt_total_P9_cmd.Text = string.Format
(
   "{0} €uros H.T.",
   Val.ToString("D2")
); 
is more suitable.
 
Share this answer
 
v2
Comments
LSB71 17-Jan-20 11:42am    
Excuse me, but I don't get the result I want.
The answer from (phil.o) gives me this for example.
Txt_total_P9_cmd.Text = string.Format("{0} €uros H.T.", Math.Round(Val, 2)); = 1254,8
I would like two digits after the decimal point like this (1254.80)
and like this :
Txt_total_P9_cmd.Text = Math.Round(Convert.ToString(Val), 2) + " €uros H.T";
I have the following error (impossible conversion from string to duplicate)
phil.o 17-Jan-20 11:51am    
Please see my updated answer.
Thank you,
I changed the format like this : string.Format("{0:0.00}
And I get my result well.
<pre lang="c#">
Txt_total_P9_cmd.Text = string.Format("{0:0.00} Euros H.T.", Math.Round(Val, 2));

Thank you phil.o
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900