473,386 Members | 1,647 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,386 software developers and data experts.

convert string to a float

I am needing some help converting a string to a float value. The string could be in any of the following formats: x x.y x/y. Obviously, I am having issues w/ the fraction string. The other formats are very easy. I have searched other places online but I cannot find anything on the fraction format. Any suggestions for this fairly n00b would be appreciated.
Jul 10 '07 #1
3 1357
TRScheel
638 Expert 512MB
I am needing some help converting a string to a float value. The string could be in any of the following formats: x x.y x/y. Obviously, I am having issues w/ the fraction string. The other formats are very easy. I have searched other places online but I cannot find anything on the fraction format. Any suggestions for this fairly n00b would be appreciated.

Well if you are going to take those three formats, you should first ensure that your string is of a proper format. Once there, you need to do two different things. If its one of the first two formats, just parse it. If its the last, you need to split it by the / and then check each of the two numbers, which I assume, each can be a form of the first two (hence, you can have x.y/z or even a.b/x.y).

Here is some sample code:

Expand|Select|Wrap|Line Numbers
  1. [STAThread]
  2. static void Main(string[] args)
  3. {
  4.     Console.WriteLine(ParseStringForDoubleExpression("5.3"));
  5.     Console.WriteLine(ParseStringForDoubleExpression("7"));
  6.     Console.WriteLine(ParseStringForDoubleExpression("4/5.4"));
  7.     try
  8.     {
  9.         Console.WriteLine(ParseStringForDoubleExpression("4/5/3"));
  10.     }
  11.     catch
  12.     {
  13.         Console.WriteLine("Exception handled");
  14.     }
  15.     Console.ReadKey(true);
  16. }
  17.  
  18. private static double ParseStringForDoubleExpression(string value)
  19. {
  20.     double result = 0.0;
  21.     if (string.IsNullOrEmpty(value))
  22.         throw new NullReferenceException("Parameter 'value' cannot be null or empty");
  23.  
  24.     if (value.Contains("/"))
  25.     {
  26.         result = ParseForDivision(value);
  27.     }
  28.     else
  29.     {
  30.         result = GetDoubleValue(value);
  31.     }
  32.  
  33.     return result;
  34. }
  35.  
  36. private static double ParseForDivision(string value)
  37. {
  38.     if (value.Contains("/"))
  39.     {
  40.         if (value.Split('/').Length != 2)
  41.             throw new Exception("Parameter 'value' is of incorrect format. Acceptable formats are: X or X.Y or X/Y");
  42.     }
  43.     else
  44.     {
  45.         throw new Exception("Parameter 'value' is of incorrect format. Acceptable formats are: X or X.Y or X/Y");
  46.     }
  47.  
  48.     double firstResult = GetDoubleValue(value.Split('/')[0]);
  49.     double secondResult = GetDoubleValue(value.Split('/')[1]);
  50.  
  51.     return firstResult / secondResult;
  52. }
  53.  
  54. private static double GetDoubleValue(string value)
  55. {
  56.     long placeHolder;
  57.     double result;
  58.     if (CheckForLong(value, out placeHolder))
  59.     {
  60.         result = placeHolder;
  61.     }
  62.     else if (CheckForDouble(value, out result))
  63.     { }
  64.     else
  65.     {
  66.         throw new Exception("Parameter 'value' is of incorrect format. Acceptable formats are: X or X.Y or X/Y");
  67.     }
  68.  
  69.     return result;
  70. }
  71.  
  72. private static bool CheckForDouble(string value, out double result)
  73. {
  74.     if (double.TryParse(value, out result))
  75.     {
  76.         if (value == result.ToString())
  77.         {
  78.             return true;
  79.         }
  80.     }
  81.  
  82.     return false;
  83. }
  84.  
  85. private static bool CheckForLong(string value, out long result)
  86. {
  87.     if (long.TryParse(value, out result))
  88.     {
  89.         if (value == result.ToString())
  90.         {
  91.             return true;
  92.         }
  93.     }
  94.  
  95.     return false;
  96. }
  97.  
Jul 10 '07 #2
I should have clarified previously, but I am developing in C# using Visual Studio 2003. There isn't oString.contains method, which is the tricky part. I already tried using that. I do appreciate the help though. If there are any other suggestions I will gladly take them.
Jul 10 '07 #3
TRScheel
638 Expert 512MB
I should have clarified previously, but I am developing in C# using Visual Studio 2003. There isn't oString.contains method, which is the tricky part. I already tried using that. I do appreciate the help though. If there are any other suggestions I will gladly take them.
Use IndexOf instead then. If it returns -1, it doesnt exist. If it returns a value, split to that value, and check from that value on. If it isnt -1, '/' appears more then once.

Example:

Expand|Select|Wrap|Line Numbers
  1. string myString = "whatever";
  2. if(myString.IndexOf('/') != -1)
  3. {
  4.      if(myString.Substring(myString.IndexOf('/'), myString.Length - myString.IndexOf('/') - 1) != -1)
  5.      { // too many '/' }
  6.      else
  7.      { // right amount
  8.      }
  9. }
  10.  
Jul 10 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Cally | last post by:
Hello, I would like to convert a field from ntext field found in one database table to float field found in another database table. The reason why I want to do this is a long one. I have...
4
by: jaijai_kumar | last post by:
Select Cast('100.1234' as float) give me the result 100.1234 Now when I convert it back to char I want exactly 100.1234 Select Convert(char(100),Cast('100.1234' as float)) Gives me 100.123 (Here...
4
by: aevans1108 | last post by:
expanding this message to microsoft.public.dotnet.xml Greetings Please direct me to the right group if this is an inappropriate place to post this question. Thanks. I want to format a...
2
by: Chi Tang | last post by:
Hi, I try to convert a string to a float but it alway comes out with extra value. For example, the string input is '12.6' but the output is '12.6000003814697' The following is my code to do...
7
by: shellon | last post by:
Hi all: I want to convert the float number to sortable integer, like the function float2rawInt() in java, but I don't know the internal expression of float, appreciate your help!
2
by: lisasahu | last post by:
how to convert float to string like there is atof atoi and itoa but is ther any method to convert float to string
0
by: jeff_rowa | last post by:
Hi guyz, Could anyone please tell me how can I convert an array of floats to a string? I know that I can use this code to convert one float to a string but what is the best way for an array of...
7
by: tereglow | last post by:
Hello, I am a complete newbie to Python and am accustomed to coding in PHP/ Perl/Shell. I am trying to do the following: I have a string: cpuSpeed = 'Speed: 1000000000' What I would...
12
by: Peter | last post by:
Trying to convert string to byte array. the following code returns byte array of {107, 62, 194, 139, 64} how can I convert this string to a byte array of {107, 62, 139, 65} ...
9
by: Marco Nef | last post by:
Hi there I'm looking for a template class that converts the template argument to a string, so something like the following should work: Convert<float>::Get() == "float"; Convert<3>::Get() ==...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...

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.