473,785 Members | 2,843 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 5974
One way you could do this is brute force string work using IndexOfAny
and then dounble.TryPars e.

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.TryPa rse(str.Substri ng(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***@syncfusi on.comwrote in message
news:11******** **************@ a34g2000cwb.goo glegroups.com.. .
One way you could do this is brute force string work using IndexOfAny
and then dounble.TryPars e.

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.TryPa rse(str.Substri ng(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.WriteLi ne(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.TryPa rse(s[i], System.Globaliz ation.NumberSty les.Any,
null, out d))
{
d = mult * d;
Console.WriteLi ne(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***@syncfusi on.comwrote in message
news:11******** **************@ v33g2000cwv.goo glegroups.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.WriteLi ne(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.TryPa rse(s[i], System.Globaliz ation.NumberSty les.Any,
null, out d))
{
d = mult * d;
Console.WriteLi ne(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.co mwrote in message news:%2******** ********@TK2MSF TNGP03.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
73873
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 on (SELECT COUNT(*) FROM ProdCat WHERE ProdCat.Pcat_VendID=Vendors.Vend_ID). I want to concatenate...
32
14899
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
29245
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 ConvertHundreds(ByVal MyNumber As String) As String etc.
11
1923
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
17174
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 suggest an even faster method I'd like to hear from you. Also, if anyone can tell me why Regex is...
4
17787
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
6028
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 kinda funny. I know I can write "Enter unit of temp that you want converted using (F)ahrenheit,...
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
9645
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10152
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7500
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6740
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
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
2
3650
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.