Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a number to 2 decimal places in Java

Tags:

java

decimal

I want to convert a number to a 2 decimal places (Always show two decimal places) in runtime. I tried some code but it only does, as shown below

 20.03034 >> 20.03  20.3 >> 20.3  ( my code only rounds not converts ) 

however, I want it to do this:

 20.03034 >> 20.03  20.3 >> 20.30 (convert it to two decimal places) 

My code below:

angle = a variable angle_screen =  a variable  DecimalFormat df = new DecimalFormat("#.##"); angle = Double.valueOf(df.format(angle)); angle_screen.setText(String.valueOf(angle) + tmp); 

Any help on how to do this would be great, thanks.

like image 256
Jack Trowbridge Avatar asked Jan 08 '12 17:01

Jack Trowbridge


People also ask

How do you move a number to 2 decimal places?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.

How do you round a double to 2 decimal places in Java?

Round of a double to Two Decimal Places Using Math. round(double*100.0)/100.0. The Math. round() method is used in Java to round a given number to its nearest integer.


2 Answers

try this new DecimalFormat("#.00");

update:

    double angle = 20.3034;      DecimalFormat df = new DecimalFormat("#.00");     String angleFormated = df.format(angle);     System.out.println(angleFormated); //output 20.30 

Your code wasn't using the decimalformat correctly

The 0 in the pattern means an obligatory digit, the # means optional digit.

update 2: check bellow answer

If you want 0.2677 formatted as 0.27 you should use new DecimalFormat("0.00"); otherwise it will be .27

like image 162
Rogel Garcia Avatar answered Oct 08 '22 22:10

Rogel Garcia


DecimalFormat df=new DecimalFormat("0.00"); 

Use this code to get exact two decimal points. Even if the value is 0.0 it will give u 0.00 as output.

Instead if you use:

DecimalFormat df=new DecimalFormat("#.00");   

It wont convert 0.2659 into 0.27. You will get an answer like .27.

like image 30
Anto Robinson Avatar answered Oct 08 '22 23:10

Anto Robinson