Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
273 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...