GMLscripts.com

Discuss and collaborate on GML scripts
Invert

You are not logged in.

#1 2015-08-27 10:23:54

gnysek
Member
Registered: 2011-12-29
Posts: 36

string_to_real()

Since real("x1.5") will return 0, and string_digits("x1.5") will return 15 (removes decimal point), I wanted to create a function which will remove everything else than numbers and decimal point from string and create a number from it. So:

string_to_real("x23e") - 23
string_to_real("x1.5") - 1.5
string_to_real("x1.5x9") - 1.59

Expand///string_to_real(str)

    var str = argument0;
    if (is_real(str)) return str;
    var out = "";
    var char, code;
    
    for(i = 1; i <= string_length(str); i++) {
        char = string_char_at(str, i);
        code = ord(char);    
        if ((code >= $30 and code <= $39)) {
            out += char;
        } else if (char == "." or char == ",") { //some countries uses , instead of . as separator
            out += char;
        }
    }
    
    if string_length(out) == 0 return 0 else return real(out);

Offline

#2 2015-08-28 05:07:59

xot
Administrator
Registered: 2007-08-18
Posts: 1,239

Re: string_to_real()

This is an interesting script. I can imagine it simplifying things in a variety situations. Thanks for the submission.


Abusing forum power since 1986.

Offline

#3 2016-04-10 09:56:22

gnysek
Member
Registered: 2011-12-29
Posts: 36

Re: string_to_real()

I forgot about negative numbers:

Expand///string_to_real(str)

    var str = argument0;
    if (is_real(str)) return str;
    var out = "";
    var char, code;
    var sign = 1;
    
    for(i = 1; i <= string_length(str); i++) {
        char = string_char_at(str, i);
        code = ord(char);    
        if ((code >= $30 and code <= $39)) {
            out += char;
        } else if (char == "." or char == ",") { //some countries uses , instead of . as separator
            out += ".";
        } else if (char == "-") {
            sign *= -1;
        }
    }
    
    if string_length(out) == 0 return 0 else return real(out) * sign;

So in case there is string "-10" it should return -10, and if it's "--15" it should give 15, as it's double negative. Also fixed line with comma separator, as it should be converted always to "."

Offline

Board footer

Powered by FluxBB