Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!