473,327 Members | 1,997 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

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 5950
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
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)...
32
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...
7
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
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...
11
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...
3
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...
4
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
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...
4
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
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shćllîpôpď 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.