How to print 0.10 instead of 0.1 in Java?

Asked

Viewed 104 times

3

The code below counts how many letters there are in a word and multiplies by 0.01. The problem is that I want when a 10 letter word, for example, is typed, to have an output of 0.10 and not 0.1.

import java.util.Scanner;
import java.text.DecimalFormat;

public class MedidaDeTempo{

    public static void main(String[] args){
        Scanner ler = new Scanner(System.in);
        String teste;
        int C, tamanho, i = 0;
        double T;

        C = ler.nextInt();

        do{
            i++;
            teste = ler.nextLine();
            tamanho = teste.length();
            T = tamanho * 0.01;

            if(T > 0.00){
                DecimalFormat df = new DecimalFormat("0.##");
                String decimal = df.format(T);
                System.out.printf(decimal + "\n");
            }
        } while(i <= C);
    }
}

1 answer

5


Thus?

System.out.format("%.2f%n", decimal);

I put in the Github for future reference.

You need to specify the number of decimals and not how it should be formatted. I hope you do not need accuracy, this solution does not guarantee this.

  • Thanks! I figured out what I was doing wrong! I was putting "%. 00f" instead of "%. 2f", as you put it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.