Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Language invariant Double.ToString()

Tags:

c#

.net

vb.net

I am passing a double across a network, currently I do

double value = 0.25;
string networkMsg = "command " + value;

the networkMsg is fine in english where its 0.25 and french where its 0,25, but when i go from a french computer to an english computer one side is making it 0.25 and the other is trying to read 0,25.

So i can to use region invariant methods in my code.

I have found Val(networkMsg) that will always read 0.25 no matter the region.

but I cannot find a guaranteed way of converting from value to 0.25 region invariant. would value.toString("0.0") work?

like image 500
f1wade Avatar asked Oct 10 '13 12:10

f1wade


People also ask

Can you use toString on a double?

toString() We can use Double class toString method to get the string representation of double in decimal points.

What is the argument type of double toString ()?

toString(double d) method returns a string representation of the double argument. The argument d is the double value to be converted.

How to convert double to string in c# windows application?

ToString() Method is used to convert the numeric value of the current instance to its equivalent string representation.

How to convert double to string with Decimal in java?

1. Java – Convert double to string using String. valueOf(double) method. public static String valueOf(double d) : We can convert the double primitive to String by calling valueOf() method of String class.


2 Answers

Use:

string networkMsg = "command " + value.ToString(CultureInfo.InvariantCulture);

or:

string networkMsg = string.Format(CultureInfo.InvariantCulture, "command {0}", value);

This needs using System.Globalization; in the top of your file.

Note: If you need full precision, so that you can restore the exact double again, use the Format solution with the roundtrip format {0:R}, instead of just {0}. You can use other format strings, for example {0:N4} will insert thousands separators and round to four dicimals (four digits after the decimal point).


Since C# 6.0 (2015), you can now use:

string networkMsg = FormattableString.Invariant($"command {value}");
like image 116
Jeppe Stig Nielsen Avatar answered Sep 25 '22 00:09

Jeppe Stig Nielsen


The . in the format specifier "0.0" doesn't actually mean "dot" - it means "decimal separator" - which is , in France and several other European cultures. You probably want:

value.ToString(CultureInfo.InvariantCulture)

or

value.ToString("0.0", CultureInfo.InvariantCulture)

For info, you can see this (and many other things) by inspecting the fr culture:

var decimalSeparator = CultureInfo.GetCultureInfo("fr")
            .NumberFormat.NumberDecimalSeparator;
like image 29
Marc Gravell Avatar answered Sep 22 '22 00:09

Marc Gravell