Help rounding numbers

float per = (num / (float) totbrwdbksint) * 100;

im gets the value per, as they say 29.475342. I want it to be rounded to two decimal places. Like 29.48. How to achieve this?

+3
source share
5 answers

You must do this as part of the formatting - the floating point number itself does not have the concept of “two decimal places”.

For example, you can use DecimalFormatwith the drawing "# 0.00":

import java.text.*;

public class Test
{
    public static void main(String[] args)
    {
        float y = 12.34567f;
        NumberFormat formatter = new DecimalFormat("#0.00");
        System.out.println(formatter.format(y));
    }
}
+5
source

As John implies , the format to display. The most concise way to do this is probably with a class String.

float f = 70.9999999f;
String toTwoDecPlaces = String.format("%.2f", f);

This will result in a line "71.00"

+1
source

, java, , , . , , , :

  • , , , , , , , , .
  • , ...

, /... , ... ... , 29.475342 → 29.47 , ?,.005 /.

, ... , , XX.XXXXXXXXXX(, , 27/28 ), XX.XX.

- ...

, , , .

+1

you can use the formatted printing method System.out.printf to format the print if you need it

0
source

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


All Articles