1

I'm just starting out using Java. And I came across this issue :

This is my code :

import java.util.Scanner;
public class FormatageValeurNumerique {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Entrez une valeur reelle :");
        Scanner in = new Scanner(System.in);
        float x = in.nextFloat();
//      System.out.printf("La valeur reelle est, apres formatage : %.5+,f", x);
//      Gives exception ? Why ?
//      System.out.printf("La valeur reelle est, apres formatage : %+.5,f", x);
//      Gives exception ? Why ?
        System.out.printf("La valeur reelle est, apres formatage : %+,.5f", x);
    }
}

Outputs :

Entrez une valeur reelle : 315136.23 La valeur reelle est, apres formatage : +315,136.21875

And this is what is expected :

Formatage de valeurs numériques

Écrivez un programme qui demande à l’usager une valeur réelle et qui l’affiche à l’écran en s’assurant d’avoir au moins 5 chiffres après la virgule, en forçant l’apparition du signe et en incluant le groupement de chiffres.

L’affichage obtenu doit être semblable au suivant:

Entrez une valeur réelle : 315136.23 La valeur réelle est, après formatage : +315,136.23000

The numbers do not match... any ideas why ?

Also if someone can explain why I'm getting exceptions depending on how I write out the flags ? Is there a priority to respect ?

4

1 回答 1

1

Don't use float except in very specific circumstances. This has nothing to do with printf and all to do with the fact that you are loosing precision when using float as your floating point type. Use double which has double the precision of float or BigDecimal which has a precision that you define.

I think that the only time I use floats is when calling Java core class methods that expect a float parameter such as some Swing constants and when setting a Swing Font's size. The additional overhead with use of double is minimal. Also you should not use float nor double for financial calculations as these require extreme precision that the floating point types do not offer. Use BigDecimal for these.

For more on the difference, please see: different-values-for-float-and-double. But mainly remember that Java float is represented internally as a 32-bit representation and double as a 64-bit representation.

于 2013-05-12T19:34:19.937 回答