Sivasubramanian
Sivasubramanian

Reputation: 955

why Double to string discards the zeroes after decimal point, how to retain the zeroes?

In scenario 1 string conversion exactly converts. ie: 1.25 (double) equals 1.25 (string) but in scenario 2, my input double is 1.0 but the converted string is 1. Why is it so?? and how to retain the zeroes after decimal during string conversion??

Scenario 1:
double input1 = 1.25;
string output1 = input1.ToString("0.################");  // output1 = "1.25"

Scenario 2:
double input2 = 1.0;
string output2 = input2.ToString("0.################");  // output2 = "1"   

What do I need to do to get the output2 as "1.0" and not "1".?? Thanks in advance.

Upvotes: 1

Views: 133

Answers (2)

Valdrinium
Valdrinium

Reputation: 1416

Hash-tag # after the decimal point in the string format indicates that the value is optional. If you wish to get the output 1.0 you need the following:

Scenario 2:
double input2 = 1.0;
string output2 = input2.ToString("0.0###############");  // output2 = "1.0"

Upvotes: 4

Martin Costello
Martin Costello

Reputation: 10863

If you use 0 instead of # you will get zeroes retained rather than removed when they are insignificant.

double input2 = 1.0;
string output2 = input2.ToString("0.0###############");  // output2 = "1.0"

Full documentation for formatting of numbers can be found on MSDN: http://msdn.microsoft.com/en-us/library/0c899ak8%28v=vs.110%29.aspx

Upvotes: 2

Related Questions