Jump to content

Splitting a string then converting to a double (C#)

toobladink

I am attempting to take a string (line from a file) and take the number from it and convert it to a double, so I can divide that number by a constant. Then I want to convert that back to a string.

 

This is what a typical line I am trying to convert looks like:

"VolumeInL": 3.848,

 

Basically it's a .json file.

 

Anyways, here's what I currently have. I have tried messing with the syntax a little bit, but I keep getting exceptions. The one I really don't quite understand is why I'm getting an out of bound exception for "num[1]".

static string process(string line)
		{
			string[] data = line.Split(' ');
			string[] num = data[1].Split(',');
			Console.WriteLine("Num value: {0}", num[1]);
			string anotherNum = Convert.ToString(num[1]);
			double number = Convert.ToDouble(anotherNum) / 3.785411784;
			//string value;
			//
  			//return value; this is reserved for when I want to convert back to a string
  			// and end up with something like: "VolumeInGal": 1.05, (or whatever 3.848/3.7854 is)
		}

One thing I have tried is using just "num" rather than "num[1]", but I can't seem to get it to convert to a double.

hi

pipes
Undervolting 5700 (not mine but important)

 

Link to comment
Share on other sites

Link to post
Share on other sites

11 minutes ago, toobladink said:

The one I really don't quite understand is why I'm getting an out of bound exception for "num[1]".

That's an easy one: in computers, the first element tends to be 0, not 1. You splitting "3.848," results in [ "3.848" ] -- there is only one position, ie. num[0] there. num[1] is nonexistent.

Hand, n. A singular instrument worn at the end of the human arm and commonly thrust into somebody’s pocket.

Link to comment
Share on other sites

Link to post
Share on other sites

Just a general tip whenever you're doing stuff like this: Printing is your friend!!

If you are manipulating some variable in many steps, and it isn't what you expect by the end, print it out every transformation. Make sure each step is doing what you want, and go from there. It sounds obvious, but it'd help a lot in this case.

Main Rig: R9 5950X @ PBO, RTX 3090, 64 GB DDR4 3666, InWin 101, Full Hardline Watercooling

Server: R7 1700X @ 4.0 GHz, GTX 1080 Ti, 32GB DDR4 3000, Cooler Master NR200P, Full Soft Watercooling

LAN Rig: R5 3600X @ PBO, RTX 2070, 32 GB DDR4 3200, Dan Case A4-SFV V4, 120mm AIO for the CPU

HTPC: i7-7700K @ 4.6 GHz, GTX 1050 Ti, 16 GB DDR4 3200, AliExpress K39, IS-47K Cooler

Router: R3 2200G @ stock, 4GB DDR4 2400, what are cases, stock cooler
 

I don't have a problem...

Link to comment
Share on other sites

Link to post
Share on other sites

12 minutes ago, WereCatf said:

That's an easy one: in computers, the first element tends to be 0, not 1. You splitting "3.848," results in [ "3.848" ] -- there is only one position, ie. num[0] there. num[1] is nonexistent.

But from what I understand, doesn't the split method split a string into an array of other strings? In the case where it executes, it should always generate two strings.

 

12 minutes ago, tarfeef101 said:

Just a general tip whenever you're doing stuff like this: Printing is your friend!!

If you are manipulating some variable in many steps, and it isn't what you expect by the end, print it out every transformation. Make sure each step is doing what you want, and go from there. It sounds obvious, but it'd help a lot in this case.

I've used the debugger in Visual Studio and the value for "num" is {string[1]}. It doesn't make any sense to me :(

hi

pipes
Undervolting 5700 (not mine but important)

 

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, toobladink said:

But from what I understand, doesn't the split method split a string into an array of other strings? In the case where it executes, it should always generate two strings.

If you split it into two strings where the comma is, what's the second string going to contain? I mean, there is nothing after the comma so, there is nothing to put into the second string and therefore there is no second string.

2 minutes ago, toobladink said:

I've used the debugger in Visual Studio and the value for "num" is {string[1]}. It doesn't make any sense to me :(

Visual Studio says num is an array of strings and contains one element in it, ie. num[0].

 

Hand, n. A singular instrument worn at the end of the human arm and commonly thrust into somebody’s pocket.

Link to comment
Share on other sites

Link to post
Share on other sites

4 minutes ago, WereCatf said:

If you split it into two strings where the comma is, what's the second string going to contain? I mean, there is nothing after the comma so, there is nothing to put into the second string and therefore there is no second string.

Visual Studio says num is an array of strings and contains one element in it, ie. num[0].

 

("3.848,").Split(',')  should return an array of length 2 containing "3.848" and an empty string

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, WereCatf said:

If you split it into two strings where the comma is, what's the second string going to contain? I mean, there is nothing after the comma so, there is nothing to put into the second string and therefore there is no second string.

So, the split works by splitting after the character?

 

How can I get just the number then?

hi

pipes
Undervolting 5700 (not mine but important)

 

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, toobladink said:

How can I get just the number then?

I've told you several times now, the number is in num[0].

Hand, n. A singular instrument worn at the end of the human arm and commonly thrust into somebody’s pocket.

Link to comment
Share on other sites

Link to post
Share on other sites

9 minutes ago, toobladink said:

So, the split works by splitting after the character?

 

How can I get just the number then?

it splits the string into an array of  strings separated by the delimeter (in your case 2 strings). The first string in the array will be the characters before the splitting character, with the second string being the characters after it. In your case, since there are no characters after the comma, you will get back an array containing the number and an empty string. The number will be the first element in the array, at index 0 

Link to comment
Share on other sites

Link to post
Share on other sites

7 minutes ago, WereCatf said:

I've told you several times now, the number is in num[0].

Somehow, still an empty string. See photo. Disregard the loop.

empty.png

hi

pipes
Undervolting 5700 (not mine but important)

 

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, toobladink said:

Somehow, still an empty string. See photo

I don't even understand why you're trying to convert a string into a string in the line above that. You could just use double number = Convert.ToDouble(num[0]);

Hand, n. A singular instrument worn at the end of the human arm and commonly thrust into somebody’s pocket.

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, WereCatf said:

I don't even understand why you're trying to convert a string into a string in the line above that. You could just use double number = Convert.ToDouble(num[0]);

It was a debugging thing - I assigned it so I could see the actual value rather than {string[1]}. Even if I modify it to

double number = Convert.ToDouble(num[0]);

it doesn't work and throws an exception.

hi

pipes
Undervolting 5700 (not mine but important)

 

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, toobladink said:

 


double number = Convert.ToDouble(num[0]);

it doesn't work and throws an exception.

The only reason why it wouldn't work is because you're splitting line wrong. What does line contain when your code throws an exception?

Hand, n. A singular instrument worn at the end of the human arm and commonly thrust into somebody’s pocket.

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, WereCatf said:

The only reason why it wouldn't work is because you're splitting line wrong. What does line contain when your code throws an exception?

"          \"HoldbackVolumeInL\": 0.0,"

data contatins: {string[12]}

 

And I believe that means it's an array, but I don't know how to view its contents.

hi

pipes
Undervolting 5700 (not mine but important)

 

Link to comment
Share on other sites

Link to post
Share on other sites

8 minutes ago, toobladink said:

"          \"HoldbackVolumeInL\": 0.0,"

There you go, then: line does not actually match the example you gave. You tell your code to split line whenever it meets a space-character, but... well, there's a whole bunch of space-characters in line, so you end up with a whole bunch of strings!

 

With the following line you can skip most of your code and just end up with the number you wanted in num:

string num = line.Split(':')[1].Trim().Split(',')[0];

Obviously, you won't use num[0] anymore, you'll just use num.

Trim() removes empty space from a string, ie. space-characters and such.

Hand, n. A singular instrument worn at the end of the human arm and commonly thrust into somebody’s pocket.

Link to comment
Share on other sites

Link to post
Share on other sites

One comment that needs to be made is that you shouldn't be string splitting a valid JSON string. 

 

You should deserialize the JSON into an object and then reference it from there. 

 

Create an object that represents your JSON string, then run:

 

JsonConvert.DeserializeObject<YourNewObject>(jsonstring)

 

That will give you much cleaner code, and you now have an object you can manipulate and deal with rather than a bunch of strings that will fail the moment someone decides to put a comma into the value. (e.g. if you are not localizing your data, then numbers coming from a system in Denmark would have a comma, not a decimal point in them).

 

You can also add JSON attributes to your class to allow it to handle cases where data is null etc. Check out Json serialization for more info. 

 

You can then create an extension of your class that has a .ToJson method that will serialize the class back to JSON which makes things a whole lot easier to work with. 

Link to comment
Share on other sites

Link to post
Share on other sites

4 hours ago, FlappyBoobs said:

One comment that needs to be made is that you shouldn't be string splitting a valid JSON string. 

 

You should deserialize the JSON into an object and then reference it from there. 

Thank you lol. I was reading down the comment and i was like ... hum know one noticed that was JSON and OP actually has no clue how to parse the original doc.

Link to comment
Share on other sites

Link to post
Share on other sites

7 hours ago, FlappyBoobs said:

One comment that needs to be made is that you shouldn't be string splitting a valid JSON string. 

 

You should deserialize the JSON into an object and then reference it from there. 

 

Create an object that represents your JSON string, then run:

 


JsonConvert.DeserializeObject<YourNewObject>(jsonstring)

 

That will give you much cleaner code, and you now have an object you can manipulate and deal with rather than a bunch of strings that will fail the moment someone decides to put a comma into the value. (e.g. if you are not localizing your data, then numbers coming from a system in Denmark would have a comma, not a decimal point in them).

 

You can also add JSON attributes to your class to allow it to handle cases where data is null etc. Check out Json serialization for more info. 

 

You can then create an extension of your class that has a .ToJson method that will serialize the class back to JSON which makes things a whole lot easier to work with. 

Sorry - I shoudlve specified that I'm copying and pasting the text and making it a .txt file. It's a one time use thing, so copying and pasting isn't a big deal. It's just... there are thousands of conversions lol.

hi

pipes
Undervolting 5700 (not mine but important)

 

Link to comment
Share on other sites

Link to post
Share on other sites

14 hours ago, toobladink said:

I've used the debugger in Visual Studio and the value for "num" is {string[1]}. It doesn't make any sense to me :(

So don't use the debugger. Just print the value to stdout. 

Main Rig: R9 5950X @ PBO, RTX 3090, 64 GB DDR4 3666, InWin 101, Full Hardline Watercooling

Server: R7 1700X @ 4.0 GHz, GTX 1080 Ti, 32GB DDR4 3000, Cooler Master NR200P, Full Soft Watercooling

LAN Rig: R5 3600X @ PBO, RTX 2070, 32 GB DDR4 3200, Dan Case A4-SFV V4, 120mm AIO for the CPU

HTPC: i7-7700K @ 4.6 GHz, GTX 1050 Ti, 16 GB DDR4 3200, AliExpress K39, IS-47K Cooler

Router: R3 2200G @ stock, 4GB DDR4 2400, what are cases, stock cooler
 

I don't have a problem...

Link to comment
Share on other sites

Link to post
Share on other sites

3 hours ago, Franck said:

hum know one noticed that was JSON and OP actually has no clue how to parse the original doc

I did, but I figured that starting to talk about JSON and parsing and such would confuse OP even worse. I mean, OP doesn't seem to grasp even how Split() works, so I didn't want to make things even worse. I don't know if that was the right choice, but I just felt better to keep things where the OP was.

Hand, n. A singular instrument worn at the end of the human arm and commonly thrust into somebody’s pocket.

Link to comment
Share on other sites

Link to post
Share on other sites

6 minutes ago, WereCatf said:

I did, but I figured that starting to talk about JSON and parsing and such would confuse OP even worse. I mean, OP doesn't seem to grasp even how Split() works, so I didn't want to make things even worse. I don't know if that was the right choice, but I just felt better to keep things where the OP was.

Sorry - I never clarified I was copying and pasting it and converting to a .txt file. Honestly, I figured it might read lines the same way anyways.

 

Thank you for your help!

hi

pipes
Undervolting 5700 (not mine but important)

 

Link to comment
Share on other sites

Link to post
Share on other sites

7 hours ago, FlappyBoobs said:

One comment that needs to be made is that you shouldn't be string splitting a valid JSON string. 

 

You should deserialize the JSON into an object and then reference it from there. 

 

Create an object that represents your JSON string, then run:

 


JsonConvert.DeserializeObject<YourNewObject>(jsonstring)

 

That will give you much cleaner code, and you now have an object you can manipulate and deal with rather than a bunch of strings that will fail the moment someone decides to put a comma into the value. (e.g. if you are not localizing your data, then numbers coming from a system in Denmark would have a comma, not a decimal point in them).

 

You can also add JSON attributes to your class to allow it to handle cases where data is null etc. Check out Json serialization for more info. 

 

You can then create an extension of your class that has a .ToJson method that will serialize the class back to JSON which makes things a whole lot easier to work with. 

The main reason why I copied and pasted everything into a .txt is because I wasn't sure if there was a way to easily rename a property.

 

But it turned out that uh.. doing that would be way easier anyways. I looked it up yesterday, but sometimes a brick writes better google searches than I do, because I couldn't really find exactly what I was looking for.

 

And.. I'm more comfortable with working with strings and figured it wouldn't be any worse.

hi

pipes
Undervolting 5700 (not mine but important)

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×