简体   繁体   中英

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.

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");

您可以改用十进制类型。

decimal propertyValue = 1994.7755474452554M;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM