How to round the sum of metric value on Scripted Field in Visualization?

Hello community,

I have written a Scripted field where I am getting P&L of successful trades in a field that I'll later use in a visualization (sum of P&L of successful trades).

Code in painless:

if(doc['Type.keyword'].value == "F")
{
    return Math.round(doc['Cont P&L'].value * 100.0)/100.0;
} else {
    return 0;
}

Now when I am making a visualization where I am adding all the P&L from this field. And I get this value :
-4582.040000000001

However, I am looking at a value -4582.04.

Can you guys please help me this issue? Thanks :slight_smile:

Hi Shalvin,

I think your problem with rounding is that your parenthesis grouping for Math.round isn't including the /100.0. So you're taking your value * 100 and rounding that (rounding -458204.0000001 to -458204) and then dividing that by 100 which gives you -4582.04.

So I think this would fix it;
return Math.round((doc['Cont P&L'].value * 100.0)/100.0);

of even simpler
return Math.round(doc['Cont P&L'].value);

You can also use the format option in your scripted field to set the format to 1000 that would tell it to not show any decimal places or thousands separator. The advantage of only doing the formatting is that if you do a sum or average of the field then the end result might be more accurate.

Regards,
Lee

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