473,542 Members | 9,296 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

convert string to double and count characters

Jay
I need to convert from a string a double that is followed by a scaling character (k means *1e3,
M=*1e6, etc) then apply the scaling character. Example:

"-1.345k #comment"

I know roughly how to do this in C (using the %n in the sscanf format specifier to find the number
of characters converted) , but how do I do it in C#? My problem is how to count the number of
characters of the double (chpos in the C example) so that the scaling character can be easily found.

/* C-code example */
double doub;
int n, nchar, chpos=0
char str[] = "-1.345k #comment"

n=sscanf"(&str[chpos], "%lf%n", &doub, &nchar);
if(n==0){
... code to deal with invalid double
}else
chpos += nchar;
if(str[chpos]='k'){
doub *= 1e6;
}
...
}
Feb 6 '07 #1
6 5962
One way you could do this is brute force string work using IndexOfAny
and then dounble.TryParse.

string str = "-1.35k #comment";
int i = str.IndexOfAny(new char[]{'k', 'M', '#'});
double d = double.NaN;
if(i == -1 || str[i] == '#')
{
//error case
}
else if(double.TryParse(str.Substring(0, i), out d))
{
switch(str[i])
{
case 'k':
d *= 1000;
break;
case 'M':
d *= 1000000;
break;
default:
break;
}
}
else
{
//second error case
}
//d has the value
======================
Clay Burch
Syncfusion, Inc.

Feb 6 '07 #2
Jay
Thanks for your reply.

Sorry, but my example was a little simplified to help to illustrate my problem. A real example is

string str = "load=-1.35k source=2.3e6 sink=34,27M #comment";

If I use your technique, it misses the absence of a scaling value (which is allowed, as shown for
source=2.3e6).

If C# doesn't have a way to count the number of characters used by the double, then I guess I'll
have to write a method that does the counting, taking into account all the possible ways that a
valid double can be written.
"ClayB" <cl***@syncfusion.comwrote in message
news:11**********************@a34g2000cwb.googlegr oups.com...
One way you could do this is brute force string work using IndexOfAny
and then dounble.TryParse.

string str = "-1.35k #comment";
int i = str.IndexOfAny(new char[]{'k', 'M', '#'});
double d = double.NaN;
if(i == -1 || str[i] == '#')
{
//error case
}
else if(double.TryParse(str.Substring(0, i), out d))
{
switch(str[i])
{
case 'k':
d *= 1000;
break;
case 'M':
d *= 1000000;
break;
default:
break;
}
}
else
{
//second error case
}
//d has the value
======================
Clay Burch
Syncfusion, Inc.
Feb 6 '07 #3
If you are confident that your numbers will have the space delimiters
separating the number strings, then you can use string.Split to get an
array of the values, iterate through the values, testing the last
character for 'k' or M. The double.Parse should handle the 1.03e6 just
fine (maybe using the other overload that accepts a NumberStyles
parameter is needed, but one of them should handle the exponential
notation).
string str = "load=-1.35k source=2.3e6 sink=34,27M #comment";
Console.WriteLine(str);
string[] s = str.Split(new char[] { '=', ' '});

for(int i = 1; i < s.GetLength(0); i += 2)
{
double mult = 1;
if (s[i].EndsWith("k"))
{
mult = 1000;
s[i] = s[i].Substring(0, s[i].Length - 1);
}
else if (s[i].EndsWith("M"))
{
mult = 1000000;
s[i] = s[i].Substring(0, s[i].Length - 1);
}
double d;
if(double.TryParse(s[i], System.Globalization.NumberStyles.Any,
null, out d))
{
d = mult * d;
Console.WriteLine(d);
}
}

//output
load=-1.35k source=2.3e6 sink=34,27M #comment
-1350
2300000
3427000000

==============
Clay Burch
Syncfusion, Inc.

Feb 6 '07 #4
Jay
Thanks for you help ClayB + sorry for the late reply.

It works fine, although I'm a little worried about coping with errors. For instance, if the line
starts with "load -1.35k" rather than "load=-1.35k", the value is read, even though the syntax is
incorrect.

"ClayB" <cl***@syncfusion.comwrote in message
news:11**********************@v33g2000cwv.googlegr oups.com...
If you are confident that your numbers will have the space delimiters
separating the number strings, then you can use string.Split to get an
array of the values, iterate through the values, testing the last
character for 'k' or M. The double.Parse should handle the 1.03e6 just
fine (maybe using the other overload that accepts a NumberStyles
parameter is needed, but one of them should handle the exponential
notation).
string str = "load=-1.35k source=2.3e6 sink=34,27M #comment";
Console.WriteLine(str);
string[] s = str.Split(new char[] { '=', ' '});

for(int i = 1; i < s.GetLength(0); i += 2)
{
double mult = 1;
if (s[i].EndsWith("k"))
{
mult = 1000;
s[i] = s[i].Substring(0, s[i].Length - 1);
}
else if (s[i].EndsWith("M"))
{
mult = 1000000;
s[i] = s[i].Substring(0, s[i].Length - 1);
}
double d;
if(double.TryParse(s[i], System.Globalization.NumberStyles.Any,
null, out d))
{
d = mult * d;
Console.WriteLine(d);
}
}

//output
load=-1.35k source=2.3e6 sink=34,27M #comment
-1350
2300000
3427000000

==============
Clay Burch
Syncfusion, Inc.
Feb 8 '07 #5
Jay wrote:
Thanks for your reply.

Sorry, but my example was a little simplified to help to illustrate my problem. A real example is

string str = "load=-1.35k source=2.3e6 sink=34,27M #comment";

If I use your technique, it misses the absence of a scaling value (which is allowed, as shown for
source=2.3e6).

If C# doesn't have a way to count the number of characters used by the double, then I guess I'll
have to write a method that does the counting, taking into account all the possible ways that a
valid double can be written.

You can use a regular expression to make sure that the format is
correct, and extract the interresting information.

You can use a pattern like this:

"^load=([\-\d\.])([kM]) source=([\-\d\.](?:e\d+)?)
sink=([\d,])([kM])\s*(?:#.*)$"

This will match anything outside the parantheses literarly, except the
comment, that is optional. Inside the parantheses it will match
according to the patterns, allowing the characters used in numbers.
What's in every paranthesis pair is returned as groups.

You can make the matches stricter if you like, for example only allowing
the minus sign as first character and only allowing a single decimal
separator. You can also make some matches more relaxed, like allowing
any number of spaces between the values.

When you match the input string using the pattern, you will only get a
match if the input is correct according to the pattern. If you don't get
a match, you know that there is something wrong with the line.

--
Göran Andersson
_____
http://www.guffa.com
Feb 8 '07 #6
Jay
Thanks Göran, that's very helpful.

Jay

"Göran Andersson" <gu***@guffa.comwrote in message news:%2****************@TK2MSFTNGP03.phx.gbl...
Jay wrote:
Thanks for your reply.

Sorry, but my example was a little simplified to help to illustrate my problem. A real example is

string str = "load=-1.35k source=2.3e6 sink=34,27M #comment";

If I use your technique, it misses the absence of a scaling value (which is allowed, as shown for
source=2.3e6).

If C# doesn't have a way to count the number of characters used by the double, then I guess I'll
have to write a method that does the counting, taking into account all the possible ways that a
valid double can be written.

You can use a regular expression to make sure that the format is
correct, and extract the interresting information.

You can use a pattern like this:

"^load=([\-\d\.])([kM]) source=([\-\d\.](?:e\d+)?)
sink=([\d,])([kM])\s*(?:#.*)$"

This will match anything outside the parantheses literarly, except the
comment, that is optional. Inside the parantheses it will match
according to the patterns, allowing the characters used in numbers.
What's in every paranthesis pair is returned as groups.

You can make the matches stricter if you like, for example only allowing
the minus sign as first character and only allowing a single decimal
separator. You can also make some matches more relaxed, like allowing
any number of spaces between the values.

When you match the input string using the pattern, you will only get a
match if the input is correct according to the pattern. If you don't get
a match, you know that there is something wrong with the line.

--
Göran Andersson
_____
http://www.guffa.com
Feb 9 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
73833
by: photomonkey | last post by:
I am having a problem with a relatively simple sql query, and was hoping that somebody could help me on this forum. Basicaly the situation is that I have two tables, a Vendors table (Vendors) and a ProductCatalogue table (ProdCat). I wish to select the VendorID, and VendorName from the vendors table. Additionally I want to run a subquery...
32
14766
by: tshad | last post by:
Can you do a search for more that one string in another string? Something like: someString.IndexOf("something1","something2","something3",0) or would you have to do something like: if ((someString.IndexOf("something1",0) >= 0) || ((someString.IndexOf("something2",0) >= 0) ||
7
29176
by: patang | last post by:
I want to convert amount to words. Is there any funciton available? Example: $230.30 Two Hundred Thirty Dollars and 30/100
6
1407
by: patang | last post by:
Could someone please tell me where am I supposed to put this code. Actually my project has two forms. I created a new module and have put the following code sent by someone. All the function declaration statments (first lines) e.g. Public Function ConvertCurrencyToEnglish(ByVal MyNumber As Double) As String Private Function...
11
1900
by: Prof.Stanley | last post by:
hello , i ma new in this group and writing over the fact that i have a small project at hand,i am writing a program which can permit the input of a text of arbitary lenght,and the number of double vowels must be determined. Output:frequency of each double vowel ,must be dtermined. e.g. Later ,we will see you again OUTPUT:1xee,1xou,1xai.
3
17159
by: Dana King | last post by:
I'm looking for some other developers opinions, I'm trying to find the best way to count strings within a string using VB.net. I have tested five methods and have found the String.Replace method is the fastest and the Regex.Matches.Count to be the slowest. I posted my results and source code to my web site. If you could take a look and maybe...
4
17740
by: thinktwice | last post by:
i'm using VC++6 IDE i know i could use macros like A2T, T2A, but is there any way more decent way to do this?
5
6019
by: sjsn | last post by:
Basic C++, just started this course in school... So I'm very limited. What I'm at doing is, below I have a variable named inputTemp, which is the product of a char, F = Fahrenheit, C = Celsius and K = Kelvin... I want to be specific when asking the user for more information, such as degrees. So when I ask for degrees in F... it wont sound so...
4
5078
by: tshad | last post by:
I am trying to convert a string character to an int where the string is all numbers. I tried: int test; string stemp = "5"; test = Convert.ToInt32(stemp); But test is equal to 53.
0
7384
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7322
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7567
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7718
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7316
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
5862
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5239
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3372
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1790
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.