0

I am writing a program to get data from microcontroller to PC. The data is in float format. I tried to convert the string into float using Convert.ToSingle(string), but the conversion result is wrong:

  1. "0.11" is converted to 11, sometimes 12.
  2. "0.10" is converted to 10. etc

As you can see, it is losing the leading 0. , which is unexpected. How could this happen?

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
swdmnd
  • 113
  • 12

1 Answers1

5

Your problem is culture specific. In some cultures float numbers are separated by a , and in some they are separated by a .

In your case

String a = "0,11";
Convert.ToSingle(a)

should result in your desired outcome of 0,11.

So you should explicitly specify a relevant culture that uses . as decimal separator. One possibility is the invariant culture which is based on the English language.

Try the following:

String a = "0.11";
Convert.ToSingle(a, CultureInfo.InvariantCulture)
Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
  • 1
    You: _make it invariant so both possibilities can be accepted_ No, the `InvariantCulture` uses only `"."` for the `NumberDecimalSeparator`, and only `","` for the `NumberGroupSeparator`. It does not allow "both possibilities". For example, `Convert.ToSingle("23.456,78", CultureInfo.InvariantCulture)` does not succeed. And `Convert.ToSingle("23456,78", CultureInfo.InvariantCulture)` produces a value near 2.3 million, not 23 thousand. – Jeppe Stig Nielsen Jul 13 '19 at 14:09
  • @JeppeStigNielsen thank you for the detailed correction of my answer, would you care to edit it and add the corrective details from your comment? – Mong Zhu Jul 13 '19 at 19:33