Painless - how to convert float number to 'pt,BR' locale with one decimal digit?

Hi everyone,

I have a script_field for converting a float field value into an one digit value in 'pt,BR' locale. I'm doing the following:

script: {
            inline: "if (params['_source']['my_field'] != null) { [ (Math.round(params['_source']['my_field'] * 100.0)/100.0) ] }"
        }

At this point, I've just rounded it to one digit decimal. I'd like to set a Locale format. Is it possible?

I've tried

script: {
            inline: "if (params['_source']['my_field'] != null) { [ new Float(Float.toString(Math.round(params['_source']['my_field'] * 100.0)/100.0).replace('.', ',')) ] }"
        }

But got an exception, which I couldn't detect the real problem. Can't I use the Float class here?

Does anybody have a hint?

Thank you,

Guilherme

In the second script try the following:

script: {
            inline: "if (params['_source']['my_field'] != null) { return Float.toString(Math.round((float)params['_source']['my_field'] * 100.0F)/100.0F).replace('.', ','))  }"
        }

The errors you are seeing are probably one that says Painless doesn't support new Float, instead use Float.valueOf. API (https://www.elastic.co/guide/en/elasticsearch/painless/7.x/painless-api-reference.html). Then you will probably receive errors about how double cannot be cast to float. If you want to use float you will have to specify the values as floats using casting, otherwise values will be promoted to double in the script shown here (https://www.elastic.co/guide/en/elasticsearch/painless/7.x/painless-casting.html#promotion)

Thank you, @Jack_Conradson! It worked perfectly.

Regards!

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