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?
toString() We can use Double class toString method to get the string representation of double in decimal points.
toString(double d) method returns a string representation of the double argument. The argument d is the double value to be converted.
ToString() Method is used to convert the numeric value of the current instance to its equivalent string representation.
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.
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}");
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With