[solved] Can't succeed to convert string to float

9 years 1 month ago - 9 years 1 month ago #696 by Xavier
No, it changes nothing:
Console.WriteLine("p.Value={0}, p1.Value={1}, p1.DecimalValue={2:F3}, f={3:F1}",p.Value,p1.Value,p1.DecimalValue,f);
2015-03-03T22:03:58.8034010+01:00       INFO    MySensors       N1S3    Sensor.Temperature      21.5    -
N1S3 in program id 22 property Sensor.Temperature value 21.5
p.Value=21.5, p1.Value=21.5, p1.DecimalValue=0.000, f=0.0
I've seen with MSDN samples that changing Culture doesn't help.
You can see that what ever the Culture, floats are printed with a dot as separator.

Please Log in or Create an account to join the conversation.

9 years 1 month ago - 9 years 1 month ago #708 by Dennis
hm, no idea.

As a workaround maybe you could read the string into char array, then convert each numeric char (or each char that is not equal to ',') to integer which you write to new array, and the re-assemble the array of integers to a float?

float =
arr[0]*100
+arr[1]*10
+arr[2]
+arr[3]*.1

and so on

regards

Please Log in or Create an account to join the conversation.

9 years 1 month ago - 9 years 1 month ago #712 by Xavier

Dennis wrote: As a workaround maybe you could read the string into char array, then convert each numeric char

Thank you to worry about my problem :cheer: . And I came to the same workaround that solve the issue. It's really silly I even can't declare a const float, I have to enter a ratio of integers for that :blink:
Did you try the code in the first page of this topic? Does it work as it should or do you get the same results that me? It's a shame I couldn't get a better understanding of the problem but I have to drop it now.
For those who may be interested, here is my code and it works. Of course I don't share my real ID and pass, you'll have to enter yours or test with google's Url for the https part.
Purpose of the prog:
When humidity value on sensor N2S0 reach a threshold of 65% EasyIoT sends me an SMS through the web smsapi from Free mobile. And when it goes under 40% it sends me an other SMS.
//
//	Envoi d'un SMS via l'API Freemobile quand l'humidité de la pièce atteint un seuil critique
//	
//	cf. http://support.microsoft.com/kb/307023/fr
//  cf. https://msdn.microsoft.com/fr-fr/library/system.net.webrequestmethods.http.get%28v=vs.100%29.aspx
//  cf. https://msdn.microsoft.com/fr-fr/library/hh191443.aspx
//  cf. http://www.developpez.net/forums/d224130/dotnet/langages/csharp/csharp-convertir-string-float/#post5514865

const float maxValue = 655f/10f;		// It's silly having to write that !
const float midValue = 50;
const float minValue = 40;
const string hiMsg = "Humidity alert:\n Hum=";
const string loMsg = "Humidity is low now.";

const string FreeID = "12345678";
const string FreePW = "s3Kr3tAp1c0D3";

const string testNode = "N2S0";
enum HState : byte {None,High,Low};		// 3 states for the alert status

static HState status = HState.None;		// Remember if an alert was sent 
static Int32 count =  0;				//
static DateTime lastSMS = new DateTime(2015, 3, 1, 0, 0, 0);

/* 
  ====================================================================
  This code is running one time when program is enabled
  ====================================================================
*/
public void Setup()
{  
    // Gets a NumberFormatInfo associated with the en-US culture.
	// System.Globalization.NumberFormatInfo nfi = System.Globalization.NumberFormatInfo.InvariantInfo;
	// Console.WriteLine("\t DBG: new separator = {0}",nfi.NumberDecimalSeparator);
	// if (float.TryParse("64.6", System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture,out fValue))
	//   Console.WriteLine("\t DBG: fValue = {0]",fValue);
	// else
	//   Console.WriteLine("\t DBG: fail to convert Value = 64.6");
	// fValue = Convert.ToSingle(p.Value,nfi);        
	// fValue = float.Parse(p.Value.Replace('.',','));									// exeption: incorrect input string format
	// fValue = Single.Parse(p.Value,new System.Globalization.CultureInfo("en-US"));	// exeption: incorrect input string format
	// fValue = Single.Parse(testFloat,new System.Globalization.CultureInfo("en-US"));	// exeption: incorrect input string format

  EventHelper.ModuleChangedHandler ((o, m, p) =>
  {
    if (m.Domain == "MySensors" && m.Address == testNode && p.Property == "Sensor.Humidity" && p.Value != "NaN")
    {
	  float fValue = StrToFloat(p.Value);        
      Console.WriteLine("\t DBG: Count={0,5}, Status={1}, LastOn={2:u}, fValue={3:F2}",count,status,lastSMS,fValue);
      count ++;

      if (fValue >= maxValue && status != HState.High) {
	    SendSMS(hiMsg+p.Value+'%');
        lastSMS = DateTime.Now;
        status = HState.High;
      } else if (fValue <= minValue && status == HState.High) {
        SendSMS(loMsg);
        lastSMS = DateTime.Now;
        status = HState.Low;
      } else if (fValue > midValue && status == HState.Low)
        status = HState.None;
    }
    return true;
  });
}

/*
  ====================================================================
  This code is running periodicaly when program is enabled. 
  Cron job determine running period.
  ====================================================================

public void Run()
{
}
*/
/*
  ====================================================================
  This function send a SMS using SMSAPI from Free mobile.
  The RapidSSLCABundle.crt certificat (used by Free mobile) must be
  installed first for the https request to complete.
  Mono prior to v3.12 by default didn’t trust any SSL certificates
  And current v3.20 don't fully support framework 4.5, System.Net.Http
  namespace nor asynchronous task can be used.
  Installed version is v3.2.8 (sight)
  ====================================================================
*/
private void SendSMS(String message)
{
// string msgUrl = "http://www.google.com";		// Tested OK
// string msgUrl = "https://www.google.com";	// Should work too
  string msgUrl = "https://smsapi.free-mobile.fr/sendmsg?user="+FreeID+"&pass="+FreePW+"&msg="+message;

  
  Console.WriteLine("Sending SMS :{0}\n -> Status=",message );

  try
  {
    System.Net.WebClient client = new System.Net.WebClient();
    client.UseDefaultCredentials = true;
    //workaround for SSL certificate issue
	System.Net.ServicePointManager.ServerCertificateValidationCallback = 
  	  (sender, certificate, chain, sslPolicyErrors) => { return true; };
    //    System.Net.WebRequest.ServerCertificateValidationCallback = () => true;
	System.Net.WebRequest request = System.Net.WebRequest.Create(msgUrl);
    Console.WriteLine("request created");
//  request.Method = System.Net.WebRequestMethods.Http.Head;
    System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
    Console.WriteLine("got the response: {0}",response.StatusCode);

	if (response.StatusCode == System.Net.HttpStatusCode.OK)
  	{
      // Get the stream associated with the response, "using" equals "try/finally"
      using (System.IO.Stream rxStream = response.GetResponseStream())
      {
        // Pipes the stream to a higher level stream reader with the required encoding format. 
        using (System.IO.StreamReader rdStream = new System.IO.StreamReader(rxStream, Encoding.UTF8))
          Console.WriteLine("Response stream received: {0}",rdStream.ReadToEnd());
      }
      Console.WriteLine("Message Sent");
    }
    else
      Console.WriteLine("An error occured");
    // Close everything.
    response.Close();
  }
  catch(Exception e)
  {
     Console.WriteLine("\nException Caught!");
     Console.WriteLine(e.StackTrace);
  }
//  return 0;
}

/*
  ====================================================================
  This function simulate a Single.Parse with InvariantCulture.
  For French people decimale separator is (,) not (.), but with no reason
  Convert method fails and throw an exception.
  ====================================================================
*/
float StrToFloat(string sVal)
{
  string[] sSingle;
  float Val;
 
  sSingle = sVal.Split(new char[1] {'.'});
  Val = Convert.ToInt32(sSingle[0]) * 10 + Convert.ToInt32(sSingle[1][0]);

  return Val / 10;
}

Please Log in or Create an account to join the conversation.

9 years 1 month ago #723 by Xavier
I found the bug !
It's related to the $LANG locale variable. The issue is solved if I enter this command in the shell:
$ export LANG="en_GB.utf8"

Please Log in or Create an account to join the conversation.

Time to create page: 0.283 seconds

Forum latest

  • No posts to display.