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
516 views
in Technique[技术] by (71.8m points)

c# - Decimal data type is stripping trailing zero's when they are needed to display

A web app I'm working on (another dev wrote it) has a decimal variable that is dropping two zero's after the decimal. It does not drop the trailing 2 digits if they contain a number > 0 or a combination of. The value is coming from a text file.

Example text value is: 261.00

Example decimal variable (TotalDue) is: 261

During debug when I hover over the "TotalDue" (in sample code below) the value displays as 261 and when I expand the debugger it reads "261M":

decimal TotalDue = Convert.ToDecimal(InputRow.Substring(260, 12));

I have tried bringing it in as a string (but initially it still reads as "261" instead of 261.00) and then converting it in various ways as follows. Nothing is working!

string TotalDue = InputRow.Substring(260, 12);

strTotalDue = String.Format("{0:F2}", TotalDue);

strTotalDue = String.Format("{0:N2}", TotalDue);

strTotalDue = String.Format(TotalDue, "0.00");

strTotalDue = TotalDue.ToString("G29");  

strTotalDue = String.Format("{0:0.00}", TotalDue);

strTotalDue = TotalDue.ToString("N2");//used this one with decimal data type

What am I missing? Does it matter where the text file data originated? It started in an Access database.

UPDATE: Today (12/1/15) I realized I never marked an answer because I ended up scrapping the original code and rewriting it in C#.net. I will mark Cole Campbell's answer correct because his remarks ("construct the Decimal in a way that provides it with sufficient data regarding the precision of the input.") are what prompted me to come up with the solution I did which was to manipulate the incoming data. I did so in a method - only showing the part that matters (AmtDue) below. Reminder the incoming data was in the format of "261.00" (e.g. AmtDue = 261.00):

string AmtDue = Convert.ToString(AmountDue).Replace(".", "");           
string finalstring =  ("0000000000" + AmtDue).Substring(AmtDue.Length);
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you want two decimal places you can use the proper ToString:

string formatted = TotalDue.ToString("0.00");

> Demo <

Standard Numeric Format Strings

(by the way, ToString("D2") doesn't work)


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

...