Pregunta

I'm new to java and I've hit a sort of 'syntax learning curve' here. I was wondering how I would get the Doubles in my program i.e. "rate", to format to "#.00"?

I assume I'd have to use "DecimalFormat" to do this but I'm not quite sure how to go about using it to achieve what I want in this situation:

StringTokenizer st = new StringTokenizer(reader.readLine());

while (st.hasMoreTokens())
{   
    DecimalFormat df = new DecimalFormat("#.00");
    hours = Integer.parseInt(st.nextToken());   // Converts number of hours to double
    rate = Double.parseDouble(st.nextToken());  // Converts rate to integer

    totalCost += (hours * rate);
    System.out.println("Rate = £" + rate + "\t" + "Hours = " + hours);
}

Unfortunately I'm still at the stage where the Oracle Documentation is 95% incomprehensible to me so any helpful insights here would be most welcome :)

EDIT: printout currently looks like this...

 Rate = £8.0

Should look like this:

 Rate = £8.00
¿Fue útil?

Solución

I think this should work:

System.out.println("Rate = E" + df.format(rate) + "\t" + "Hours = " + hours);

Otros consejos

You defined the DecimalFormat, but never used it in the printing.

Display it like this:

System.out.println("Rate = £" + df.format(rate) + "\t" + "Hours = " + hours);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top