Rounding floats

Hi, guys. Can anyone tell me what is the best way to ROUND a float with 6 decimals to for instance a float with 2 decimals. ".Precision()", has the disadvantage that it includes the number of digits before the comma.

1 Like

Try
Math.round()

@E1cid , that will give me an integer.

sorry you are correct
try

Number(msg.payload.toFixed(2))

or

Math.round(float*100)/100

Why are you wanting to do this? If you are sending it to a dashboard node, for example, most of them allow you to do this at display time by using something like this in the Value Format field
{{msg.payload | number: 2}}
Generally numbers should not be rounded until they get to the display, it is not good to throw away accuracy before it is necessary.

2 Likes

The complex way, but does exactly what you wants.

var myvalue = 12.345678
var myvaluestr = myvalue.toString()
var index = myvaluestr.indexOf(".")
msg.payload= myvalue.toPrecision(index+2)

Gives 12.35

2 Likes

What is wrong with using ToFixed if it is necessary to do it in javascript? It should give exactly the same result without the additional code.

@Colin and @E1cid , you are completely right the both of you. I assumed that "Number" was truncating the float.Thanks for the answers.
To @edje11 , indeed your solution is complex and does the same, also thanks for your answer.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.