How do you round numbers in qml to two decimal places?

Solution 1:

You can use almost all the javascript syntax in QML (See http://qt-project.org/doc/qt-5/ecmascript.html).

The fastest method is Math.round(<NUM> * 100) / 100

But (<NUM>).toFixed(2) works (but is too slow according to this question on SO)

The following snippet of code presents both implementations:

import QtQuick 2.0
import Ubuntu.Components 0.1

MainView {
    id: root
    width: units.gu(50)
    height: units.gu(80)

    property var my_number: Math.round(33.088117576394794 * 100) / 100;
    property var my_number2: (33.088117576394794).toFixed(2);

    Component.onCompleted: {
        console.log(my_number)
        console.log(my_number2)
    }
}