1

Using C#, I have 5 strings that are reading data from a temperature sensor on an Arduino board:

string currentTemp1 = serialPort1.ReadLine();
Thread.Sleep(1000);
string currentTemp2 = serialPort1.ReadLine();
Thread.Sleep(1000);..... and so on.

This is returning the values into the strings such as: 19.45, 19.45, 19.50, 19.45, 19.50.

I've tried a bit of research into trying to get the average, but am having problems working out how to convert the strings with the 2 decimal places into an Integer, and then getting the average.

Can someone please point me in the right direction.

The Woo
  • 17,809
  • 26
  • 57
  • 71

1 Answers1

7

The problem is that you don't want to parse the strings into integers. You should use float/double/decimal instead:

var temp1 = float.Parse(currentTemp1);
var temp2 = float.Parse(currentTemp2);
var average = (temp1 + temp2) / 2;

Or, you could use a loop if there's a variable number of integers:

var temps = currentTemp1.Split(", ");
float total;
foreach (var t in temps)
{
    total += float.Parse(t);
}
var average = total / temps.Length;
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • 1
    Lacking other information about the problem, the example should use `decimal` rather than `float` since it offers the most precision. – Eric J. Dec 17 '13 at 02:24
  • How do I pass the 'average' back so that I can push the content into a textbox please? – The Woo Dec 17 '13 at 02:24
  • @TheWoo: `return average.ToString()`. – Eric J. Dec 17 '13 at 02:24
  • Awesome. Thanks very much for all of that. – The Woo Dec 17 '13 at 02:26
  • agree with @EricJ. there will be precision error with float which will yield inconsistent results. Better to use decimal. – Carbine Dec 17 '13 at 04:39
  • @Bharath @EricJ - In this case, the OP is working in temperature. Temperatures are a scientific measure and thus not accurate enough to be thrown off by the imprecision of `float` or `double`. `float` also offers better performance when working with large sets of data. Jon Skeet's answer to this question explains it best: http://stackoverflow.com/questions/618535/what-is-the-difference-between-decimal-float-and-double-in-c – Justin Niessner Dec 17 '13 at 14:15
  • +1 for clarifying with the link, thanks @justin niessner – Carbine Dec 17 '13 at 14:34