Ubuntu – How to round numbers in qml to two decimal places

application-developmentprogrammingqmlubuntu-sdk

I have these ridiculously long real numbers such as 33.088117576394794, and I am trying to convert them to doubles (Two decimal places). So in this case, I want 33.09.

How do you do this in QML?

Best Answer

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)
    }
}