Duvida em questão do TestKiller

2 respostas
luistiagos

neste codigo:

NumberFormat nf= NumberFormat.getInstance();
		nf.setMaximumFractionDigits(4);
		nf.setMinimumFractionDigits(2);
		String a = nf.format(3.1415926);
		String b = nf.format(2);
		System.out.println("A:"+a+" B:"+b);

Eu diria que a resposta seria: A: 2.00 e B:3.1415
porem a resposta certa é: A: 2.00 e B:3.1416

o pq disto? format faz algum tipo de arredondamento???

2 Respostas

ChronoTrigger

Faz arredondamento:

float f1 = 123.45678f;
NumberFormat nf = NumberFormat.getInstance();
System.out.print(nf.getMaximumFractionDigits() + " ");
System.out.print(nf.format(f1) + " ");
nf.setMaximumFractionDigits(5);
System.out.println(nf.format(f1) + " ");
try {
System.out.println(nf.parse("1234.567"));
nf.setParseIntegerOnly(true);
System.out.println(nf.parse("1234.567"));
} catch (ParseException pe) {
System.out.println("parse exc");
}

This, on our JVM, produces
3 123.457 123.45678
1234.567
1234
Notice that in this case, the initial number of fractional digits for the default
NumberFormat is three: and that the format() method rounds f1’s value, it
doesn’t truncate it. After changing nf’s fractional digits, the entire value of f1 is
displayed. Next, notice that the parse() method must run in a try/catch block
and that the setParseIntegerOnly() method takes a boolean and in this
case, causes subsequent calls to parse() to return only the integer part of Strings
formatted as floating-point numbers.

renan_

Exatamente, faz arredondamento :slight_smile:

Criado 24 de julho de 2008
Ultima resposta 24 de jul. de 2008
Respostas 2
Participantes 3