delphidelphi-xe4livebindings

Using Format in a livebindings CustomFormat


I'm trying to use LiveBindings to format a number for display in a TEdit on a FireMonkey form.

I'm trying to use the Format method in the CustomFormat of the binding to format the number with two decimal places.

I can 'hard code' the output:

Format("Hello", %s)

which is working, but I can't work out what formatting string to use. If I try a standard formatting string such as,

Format("%.2f", %s)

I get a runtime error "Format invalid or incompatible with argument".

Indeed I get an error whenever I include a % symbol in the format string, so I'm guessing Format takes a different type of argument, but I can't find any documentation to say what the correct format string is.


Solution

  • The parameter is passed into CustomFormat as %s. The bindings system preparses out this parameter before the data is passed onto the evaluator. Thus any other % symbols in the CustomFormat string will give an error.

    As with a normal format string you can include a literal % sign by putting a double % (i.e. %%).

    So, any %s in the format string need to be converted to %%, e.g.

    Format('%%.2f', %s)
    

    which gets parsed out to

    Format('%.2f', 67.66666)
    

    and then parsed down to

    67.67
    

    for display.

    If you want to include a literal % in the final output you need to put a quadrupal %, e.g.

    Format('%%.2f%%%%', %s)
    

    becomes

    Format('%.2f%%', 67.6666)
    

    and displays as

    67.67%
    

    Note: The normal format function takes a final parameter which is an array of values. The Format method in the bindings system takes a variable length list of parameters.

    Also, the method names are case sensitive. 'Format' is correct, 'format' will fail.