PDA

View Full Version : Convert string to float


Tibbar
06-09-2007, 08:02 PM
MEL seems to lack basic data type conversion functions. I tried searching for this on the forums, but the search function here seems to be broken.

If I parse a string from a data file that happens to be a float, how do I convert "6.5" into the float 6.5?

Thanks.

alexnardini
06-09-2007, 10:36 PM
Tibbar,
you can accomplish the conversion in the following way:

/////////////////////////////////////////////////////////////////////////
string $value = "6.5";

// here we are converting your string into a float value.
float $conversion = (float)($value);

// just a sum between two floats as a test.
float $add = 3.5;
float $sum = $conversion + $add;

print ($sum);
/////////////////////////////////////////////////////////////////////////

If the string "value" coming from your data-file si stored correctly without
any additional char,
performing this conversion is not a problem at all.



Also, you can even perform your conversion on-the-fly without
the necessity to convert it first for later use, like in the example below:

/////////////////////////////////////////////////////////////////////////
string $value = "6.5";
float $add = 3.5;

// here we are converting your string into a float value on-the-fly.
float $sum = (float)($value) + $add;

print ($sum);
/////////////////////////////////////////////////////////////////////////

AtrusDni
06-10-2007, 02:25 AM
Or to simplify it:
string $test = "6.5";
float $test2 = $test;
float $test3 = ($test2 + 1);

And yes, what the hell is up with the search function? It is broken and stupid CGTalk wont answer my e-mails concerning this problem. Im glad to know im not the only person with this problem.

alexnardini
06-10-2007, 02:57 AM
Or even more simple :):

string $test = "6.5";
float $test2 = ((float)($test) + 1);


And yes, the search does'nt work for me too.

tbaypaul
06-10-2007, 04:39 PM
No, that is NOT simplier.....you don't have a variable with the answer! I'm studing O(n) right now, so I had to chime in.

Tibbar
06-10-2007, 10:07 PM
Thanks, guys. I made the mistake of not casting when I first attempted:

string $value = "6.5";
float $i = 4+$value;
print $i;

Strangely enough, this concatenates $value onto 4 yielding 46.5, even though $i is defined as a float.

CGTalk Moderation
06-10-2007, 10:07 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.