Kalai
Kalai

Reputation: 297

How to convert the double value to string without losing the data in c#

I have a double value as below

double propertyValue = 1994.7755474452554;

When i convert this double value to a string

string value = propertyValue.ToString();

it gives the value "1994.77554744526"

It has rounded off the last digits 2554 to 26.

But I do not want to round the value. Share your ideas.

Upvotes: 4

Views: 4489

Answers (4)

Ambrish Pathak
Ambrish Pathak

Reputation: 3968

You can cast double to decimal and use the default ToString() like this:

Double propertyValue = 1994.77554744526;
var str = ((decimal)propertyValue).ToString();
//str will hold 1994.77554744526

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

I can't reproduce the misbehaviour; you've experienced a representation effect: it's ToString() puts double like that.

  string source = "1994.7755474452554";

  double d = double.Parse(source, CultureInfo.InvariantCulture);

  string test = d.ToString("R", CultureInfo.InvariantCulture);

  Console.Write(source.Equals(test) ? "OK" : "Rounded !!!");

Outcome is OK. Please, notice "R" format string:

The Round-trip ("R") Format Specifier

https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx#RFormatString

Upvotes: 1

ViVi
ViVi

Reputation: 4464

By default the .ToString() method of Double returns 15 digits of precision. If you want the full 17 digits that the double value holds internally, you need to pass the "G17" format specifier to the method.

String s = value.ToString("G17");

This will prevent the rounding off of double value when converted to string.

value = propertyValue.ToString("G17");

Upvotes: 5

Ben
Ben

Reputation: 514

You could use decimal type instead.

decimal propertyValue = 1994.7755474452554M;

Upvotes: 1

Related Questions