0

I have a document with cd field is 44.4 When i using "script_fields as below :

"doc['cd'].value + 1"

script_fields value will return 45.400001525878906

Please help me to use script_fields value return to 45.4

1
  • Now check with the below. Know me if any query. Thanks Commented Oct 6, 2016 at 6:54

1 Answer 1

4

For rounding up your floating point values use Math.round() function. The below will return the value after two decimal places.

Math.round(doc['your_custom_type_var'].value * 100.0)/100.0

If you want to round up after 3 decimal places then change the value as like:

Math.round(doc['your_custom_type_var'].value * 1000.0)/1000.0

For your case do the followings :

Math.round((doc['cd'].value + 1) * 10.0 - 0.5 )/10.0 // -0.5 for getting the correct result. For this 45.401 and 45.601 both will return 45.6

Notes

Math.round() function returns the closest int to the argument. For example

Math.round(45.40000152) // will return the value 45
Math.round(45.60000152) // will return the value 46

To get the correct answer you can substitute 0.5 to the actual number and then rounding up.Then it will return the value which we want to get.

First we multiple the value with 10.0 for moving the decimal place one unit right(for the above value 454.0000152). After rounding this cuts of the floating point values(for the above value 454), and so we divide the whole numbers by 10.0 for getting the value which rounded up by one decimal place from the actual value(for the above value 45.4).

Think, it will help.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank for your answer. But cd filed is dynamic value (ex: 44.2, 44.674). So, the value will be wrong when i applying your solution. I want to script_fields that will return to 45.2, 45.674
You need to define the decimal point place you want to see. for example 1,2 or three. If you want to make dynamic position set. then use Math.pow(base, power) in the place of 10.0. Give feedback if any query
And for rounding problem, I am fixing my answer
Now, check the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.