0

I was reading my old notes and found a question where a number with two decimal point is converted to a single decimal point. I looked around for answer and couldn't find it. I cannot keep it string as I have to return as a float and compare it. Math.round was rounding it bad and ceil and floor was giving me error. I came up with this solution.

public class floatRounding{
 public static void main(String[] args){
  //System.out.println(temperature((float)32.34));
 // System.out.println(temperature((float)32.35));
  if (temperature((float)32.34)<temperature((float)32.35)){
     System.out.println("Here"); 
  }
}

public static float temperature(float t){
  float newt;
  //newt=Math.round(t);

  String tem=String.format("%.1f",(t+.009));
  newt=Float.parseFloat(tem);
  System.out.println(newt);
  return newt;
}
}

Is there a better solution if I am not using decimal format like in this solution How to round a number to n decimal places in Java

Thanks in advance. Please forgive if its a dumb question.

Community
  • 1
  • 1
ranjutk
  • 3
  • 6

1 Answers1

1

You could do something like this:

     double x = 1.234;
     double y = Math.round(x * 10.0) / 10.0; // => 1.2
     System.out.println(y);

This rounds the decimal to the one decimal point, the code is much shorter. Hope this helps, if so accept the answer :)

beastlyCoder
  • 2,349
  • 4
  • 25
  • 52