Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim Double to 2 decimal places

Tags:

java

should be an easy one. I originally was gonna do this in javascript but have to do it prior to setting to the form in my handler page. Anyway I need to make these values have 2 decimal places. Ex 219333.5888888 needs to be 219333.58. Is there a trim function or something?

 form.setUnitRepairCost(Double.toString(jobPlanBean.getUnitTotalCost()));   //UNIT REPAIR COST  form.setUnitMaterialCost(Double.toString(jobPlanBean.getUnitTotalMaterialCost())); //UNIT MATERIAL COST 
like image 638
Doc Holiday Avatar asked Nov 15 '11 13:11

Doc Holiday


People also ask

How do you truncate a double to two decimal places?

Shift the decimal of the given value to the given decimal point by multiplying 10^n. Take the floor of the number and divide the number by 10^n. The final value is the truncated value.


2 Answers

here is the simple example to format the decimal value

import java.text.*;  public class DecimalPlaces {      public static void main(String[] args) {          double d = 1.234567;         DecimalFormat df = new DecimalFormat("#.##");         System.out.print(df.format(d));     }  } 
like image 190
Pratik Avatar answered Oct 08 '22 22:10

Pratik


multiply the double by 100.0 and cast this to an int then take that int and cast it to a double and divide by 100.0

    int temp = (int)(longDouble*100.0);     double shortDouble = ((double)temp)/100.0; 
like image 30
Brandon Buchta Avatar answered Oct 08 '22 22:10

Brandon Buchta