Search code examples
variableslua

Move decimal point | Lua


I have a variable

a = 1.2345

now I want to move the comma position to get

a = 123.45

How can I achieve this, without hardcoding it?


Solution

  • You don't have a variable a that holds the number 1,2345 (1.2345).

    The comma (,) is used to delimit multiple values in Lua, so in your first example a is 1 and 2345 gets discarded and in your second example a is 123 and 45 gets discarded.

    Lua doesn't support numbers in German locale. If you want a decimal point, use a decimal point (.). Your first example was probably intended to be a = 1.2345 and your second one a = 123.45.

    Now if you want to move the "comma position" (= "decimal point") right by two positions, that's equivalent to multiplying a by 10^2 = 100 in the decimal system:

    a = 1.2345
    a = a * 100
    print(a) -- 123.45
    

    in general, if you want to shift by n places in the decimal system:

    a = 1.2345
    n = 2
    
    a = a * 10^n
    
    print(a) -- 123.45