Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

c# - Convert string value into decimal with proper decimal points

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...