Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
Two digits after dot in toString

I managed to make these two classess, but "score" has to have 7 digits after the dot. I cannot modify Main class. I think I should use String.format("%.7f", ...) but I don't know where. Please help.

MAIN:

public class Main {
    public static void main(String[] args) {
        Calc c = new Calc();
        String score = c.doCalc(args[0]);
        System.out.println(score);
    }
}

CALC:

public class Calc {
    public String doCalc(String cmd) {
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");

        try {
            return engine.eval(cmd).toString();
        }
        catch (ScriptException e) {
            return "Invalid command to calc";
        }
    }
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Instead of using system.out.println, you should use system.out.format or system.out.printf. See a short tutorial from Oracle on using it here. Why exactly can't you modify the main class? That seems to be where your score is being printed..

over 4 years ago · Santiago Trujillo Relatório

0

You can parse the string result back to Double and feed it to String.format:

try {
    return String.format("%.7f", Double.valueOf(engine.eval(cmd).toString()));
}
catch (Exception e) {
    return "Invalid command to calc";
}

You could of course feed the result directly to String.format without the toString and valueOf round trip, like so:

return String.format("%.7f", engine.eval(cmd));

But that only works when the eval result is a valid floating point number. To deal with other cases like integers or non-numbers, you'd have to put in a few type checks and make the code look more cluttered.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda