How to limit decimal processing precision?

I have several floating point values ​​when processing with decimal places exceeding 8 digits.

How can I round these values ​​to tenths before using text() to draw them?

+4
source share
3 answers

You can format a floating point ( float or double ) x with two decimal places as follows:

 String.format("%.2f", x) 

This will give you a String .

For instance:

 String.format("%.2f", 12.34567) 

returns the string "12.35" .

+5
source

Use the nf function described in http://processing.org/reference/nf_.html . The right option allows you to specify the number of decimal places to use.

Edit: I understand that I misunderstand your question; the function associated with it truncates, not a round. The quick answer gave me the following answer:

 float round(float number, float decimal) { return (float)(round((number*pow(10, decimal))))/pow(10, decimal); } 

suggested by Markavian in the subject: http://processing.org/discourse/yabb2/YaBB.pl?num=1115073288

Hope this helps.

+4
source

You can also use DecimalFormat.

 DecimalFormat myFormatter = new DecimalFormat("#.##"); String output = myFormatter.format(12.34567); 

Check it out at docs.oracle.com

+1
source

Source: https://habr.com/ru/post/1400491/


All Articles