How to format a decimal value WITHOUT rounding to store into nullable decimal Variable in c# -
i have tried format(truncate) decimal value 4 decimal places. example, want convert decimal numbers like
31.818181818181818181818181818m or 31.818181818181818181m or 31.81818m
to
31.8181
(not rounding 31.8182) , store in nullable decimal variable. have tried following decimal formatting without rounding .net , stop rounding in c# @ number no luck nullable decimals.
here code
private decimal? returnnullabledecimal(decimal? initvalue) { //e.g. initvalue = 35m; initvalue = 35m; //just debug; decimal? outputvalue = null; if (initvalue != null) outputvalue = initvalue / (decimal)1.10; //now outputvalue 31.818181818181818181818181818m outputvalue = convert.todecimal(string.format("{0:0.0000}", outputvalue)); // <- should 31.8181 gives 31.8182 return outputvalue; }
can please help?
any decimal
can implicitly converted decimal?
, same code works in other example of truncating. if input decimal?
, you'll have check null there.
private decimal? returnnullabledecimal(decimal? initvalue) { if (initvalue.hasvalue) return math.truncate(10000 * initvalue.value) / 10000; else return null; }
Comments
Post a Comment