jtolentino
jtolentino

Reputation: 11

How to display trailing zeroes?

How do I keep the trailing zeroes like the example below. When I input -.230 with no leading zeroes it only displays -0.23 without the trailing zero. But when I input -0.230 it yields the expected result which is -0.230.

Actual output: -.230 -> -0.23
Expected output: -.230 -> -0.230

I have also tried String.Format("{0:0.000}", n) but it still does not work.

Upvotes: 0

Views: 560

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

double and decimal mentioned in the question, are quite different types. double is a binary floating point value and it doesn't keep trailing zeroes:

 double value = -0.230;

 Console.Write(value); // -0.23

Unlike double, decimal being decimal floating-point does store the trailing zeroes:

 decimal value = -0.230m; // note suffix "m" 

 Console.Write(value); // -0.230 

When represented as string values of these types can be formatted, e.g. with F3 format string which stands for "3 digits after the decimal point":

  double v1  = -0.230;
  decimal v2 = -0.230m;

  Console.Write($"{v1:f3} {v2:f3}"); 

Outcome:

  -0.230 -0.230  

Upvotes: 0

Shreekesh Murkar
Shreekesh Murkar

Reputation: 605

It seems that you are print the same number on which you have performed string.format.

Try to store the output of string.format and use that. I have used the same approach that you have used and got the expected answer. Refer following code

var n = -.23;
string str = string.Format("{0:0.000}", n);
Console.WriteLine(str); // This will give you an expected output

Console.WriteLine(n); // This won't give you an expected output

Upvotes: 1

sam-sjs
sam-sjs

Reputation: 197

Looks like you are converting to string so you can use the following

someNumber.ToString("N3");

See the MSDN docs for details on how this works, about halfway down the page it also has examples of a bunch of different codes.

Upvotes: 3

Related Questions