Calculate a Percentage

Solve this Problem
Easy5 min
Topics
Companies
Given the marks obtained and the maximum total, return the percentage scored as text with two decimal places. A percentage is a fraction rescaled so the whole is 100. The arithmetic is simple, but the order of operations and the types matter. If both values stay ints, obtained / total is 0 for anything below full marks. The two solutions show two safe orders: divide-then-scale with an explicit cast, and scale-then-divide with a double literalDouble LiteralA number written with a decimal point, such as 100.0, which the compiler treats as a double instead of an int. that makes the whole expression decimal.

Test Case 1:

Input:obtained = 437, total = 500
Output:"87.40"
Explanation:437 out of 500 is 0.874 of the whole, i.e. 87.4%.

Test Case 2:

Input:obtained = 1, total = 3
Output:"33.33"
Explanation:One third is 33.333…%, cut to two decimals.

Constraints

  • ◆1 ≤ total ≤ 1000000
  • ◆0 ≤ obtained ≤ total

Try the Dry Run

Approach & Solutions

Divide First, Then ScaleGood

Follow the definition step by step. First work out what fraction of the total was obtained — casting to double so 437 / 500 does not collapse to 0 — then multiply that fraction by 100 to express it "per hundred". Format to two decimals.

TimeO(1)
SpaceO(1)
class Solution { public String percentage(int obtained, int total) { double fraction = (double) obtained / total; double percent = fraction * 100; return String.format("%.2f", percent); } }
Scale First, Then DivideOptimal

Multiply obtained by 100.0 first and divide by total once. The 100.0 literal makes the expression decimal straight away, so no separate cast is needed, and doing a single division instead of division-then-multiplication means one rounding step instead of two.

TimeO(1)
SpaceO(1)
class Solution { public String percentage(int obtained, int total) { double percent = obtained * 100.0 / total; return String.format("%.2f", percent); } }

Related Problems