Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string value into decimal with proper decimal points

Tags:

c#

decimal

i have value stored in string format & i want to convert into decimal.

ex:

i have 11.10 stored in string format when i try to convert into decimal it give me 11.1 instead of 11.10 .

I tried it by following way

string getnumber="11.10";
decimal decinum=Convert.ToDecimal(getnumber);

i tried this also

decinum.ToString ("#.##");

but it returns string and i want this in decimal.

what could be the solution for this?

like image 520
sp_m Avatar asked Mar 16 '26 01:03

sp_m


2 Answers

As already commented 11.1 is the same value as 11.10

decimal one=11.1;
decimal two=11.10;
Console.WriteLine(one == two);

Will output true

The # formatter in the to string method means an optional digit and will supress if it is zero (and it is valid to suppress - the 0 in 4.05 wouldn't be suppressed). Try

decinum.ToString("0.00"); 

And you will see the string value of 11.10

Ideally you actually want to use something like

string input="11.10";
decimal result;

if (decimal.TryParse(input,out result)) {
   Console.WriteLine(result == 11.10);
} else {
  // The string wasn't a decimal so do something like throw an error.
}

At the end of the above code, result will be the decimal you want and "true" will be output to the console.

like image 98
Bob Vale Avatar answered Mar 18 '26 13:03

Bob Vale


this will work perfectly

string getnumber = "11.10";
decimal decinum = Math.Round(Convert.ToDecimal(getnumber), 2);
like image 27
Ankush Jain Avatar answered Mar 18 '26 14:03

Ankush Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!