Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.
Photo

String.format


  • Please log in to reply
2 replies to this topic

#1 Rod Lopez

Rod Lopez

    Advanced Member

  • Members
  • PipPipPip
  • 33 posts
  • LocationSweden

Posted 13 April 2011 - 12:26 PM

Hi there,
I am having a very simple issue, I am trying to write a few values to a 16x2 LCD, the values are, originally floats. I need to be able to see the whole set of info in a single glance.

The issue is that, by default, I end up printing too much (the number plus eight digits of precision), so my result doesn't fit on the screen at all.

My code looks like this:
	float A = 0, V = 0;
	PowerSampling.GetPower(ref V, ref A);
	Write("V " +  V + " A:" + A + " W:" + A * V);

...and the code I am trying to replicate (I am porting this from an Arduino) looks like this:
	float A, V;
	PowerSampling.GetPower(V, A);
	lcd << "V" << _FLOAT(V, 1) << " A" << _FLOAT(A,2) << " W" << _FLOAT(V * A,1);

I was intending to use String.Format but that doesn't seem to be supported... how can it be done?

#2 Rod Lopez

Rod Lopez

    Advanced Member

  • Members
  • PipPipPip
  • 33 posts
  • LocationSweden

Posted 13 April 2011 - 01:35 PM

In case anybody else has similar issues the solution is as simple as this:

Write("V " + V.ToString("F1") + " A:" + A.ToString("F2") + " W:" + (A * V).ToString("F1"));

...the funny thing is that ToString sometimes seems to return the value and sometimes the name of the type, that's why I didn't try it before. :)

#3 Mario Vernari

Mario Vernari

    Advanced Member

  • Members
  • PipPipPip
  • 1768 posts
  • LocationVenezia, Italia

Posted 13 April 2011 - 02:15 PM

No better than this:

static string Format(double v, int n)
        {
            const string padding = "0000";
            double vr = Math.Round(v, n);
            string fmt = vr.ToString();
            int pos = fmt.IndexOf('.');
            if (pos >= 0)
            {
                int ndig = fmt.Length - pos - 1;
                if (ndig < n)
                    return fmt + padding.Substring(0, n - ndig);
                else
                    return fmt.Substring(0, fmt.Length - ndig + n);
            }
            else
                return fmt + "." + padding.Substring(0, n);
        }

NOTE: does not works when the numbers needs an exponent to be formatted (e.g. 1E20)
Anyone can adjust this function?
Was not so easy!
Biggest fault of Netduino? It runs by electricity.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.