Search code examples
javastringdouble

Java: How do I set a maximum length for a Double?


How do I set a maximum length for a double?

double divSum = number1 / number2;  
String divDisplay = number1 + " / " + number2 + " = " + divSum + " "; 

JLabel divSumLabel= new JLabel();
divSumLabel.setText(divDisplay)

How do I set the maximum lenght for divSum?

1 / 3 = 0.333333... How do I set the maximum lenght, so its only 0.333?

I could do:
int maxLenght = 3;

String stringDivSum = String.valueOf(divSum);
String shortDivSum = null; 
if(stringDivSum.length() > maxLenght){
    shortDivSum = stringDivSum.substring(0, maxLenght);
}

String divDisplay = number1 + " / " + number2 + " = " + shortDivSum + " ";
But when I then do 1 / 3 it prints out 1 / 3 = 0.3?


Solution

  • Use String.format(...)

    String.format()

    double divSum = Double.parseDouble(String.format("%.3f",(double)number1  /  number2)) ;
    

    Precision, double.

    We can specify the precision of a double or float. We use the "f" to indicate a floating-point. Before this we specify ".3" to mean "three numbers after the decimal."