Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round Off decimal values in C#

how do i round off decimal values ?
Example :

decimal Value = " 19500.98"

i need to display this value to textbox with rounded off like " 19501 "

if decimal value = " 19500.43"

then

value = " 19500 "

like image 232
Guddu Avatar asked Apr 23 '09 06:04

Guddu


People also ask

Does INT round up or down in C?

So ( sizeof(int) + that remainder - one) is always >= sizeof(int). So it always rounds up.

What is 2f in C?

2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places.


2 Answers

Look at Math.Round(decimal) or the overload which takes a MidpointRounding argument.

Of course, you'll need to parse and format the value to get it from/to text. If this is input entered by the user, you should probably use decimal.TryParse, using the return value to determine whether or not the input was valid.

string text = "19500.55";
decimal value;
if (decimal.TryParse(text, out value))
{
    value = Math.Round(value);
    text = value.ToString();
    // Do something with the new text value
}
else
{
    // Tell the user their input is invalid
}
like image 75
Jon Skeet Avatar answered Sep 22 '22 18:09

Jon Skeet


Math.Round( value, 0 )

like image 25
Paul Alexander Avatar answered Sep 19 '22 18:09

Paul Alexander