Explain Floating-Point Equality After Decimal Subtraction

Quick Overview

Explain why Java decimal subtractions print alike but compare unequal, and choose between numerical tolerances, BigDecimal, and fixed-precision integers.

Explain Floating-Point Equality After Decimal Subtraction

Company: Millennium

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Technical Screen

In Java, consider: ```java double a = 0.9 - 0.8; double b = 0.8 - 0.7; System.out.println((float) a); System.out.println((float) b); System.out.println(a == b); System.out.println(a == b); ``` What is printed, why do the displayed values and equality comparison differ, and how should the comparison or representation be changed for the intended semantics? ### Clarifying Questions to Ask - Is approximate numerical equality sufficient, or are these exact decimal quantities? - What absolute or relative error is acceptable for the application's values? ```hint Formatting is not equality Casting and printing can discard distinctions that still exist in the original double values. ``` ### What a Strong Answer Covers - Binary representation error and distinct subtraction results. - The effect of casting to float without modifying a or b. - Domain-based tolerance versus exact decimal arithmetic. ### Follow-up Questions - Why is constructing a decimal object directly from a binary floating-point value risky? - When can a relative tolerance alone fail?

Overview: Explain why Java decimal subtractions print alike but compare unequal, and choose between numerical tolerances, BigDecimal, and fixed-precision integers.

Read the full Millennium Software Engineer interview experience this question came from

Millennium logo
Millennium
Nov 17, 2026
mediumSoftware EngineerTechnical ScreenSoftware Engineering Fundamentals
0
0

In Java, consider:

double a = 0.9 - 0.8;
double b = 0.8 - 0.7;
System.out.println((float) a);
System.out.println((float) b);
System.out.println(a == b);
System.out.println(a == b);

What is printed, why do the displayed values and equality comparison differ, and how should the comparison or representation be changed for the intended semantics?

Clarifying Questions to Ask Guidance

  • Is approximate numerical equality sufficient, or are these exact decimal quantities?
  • What absolute or relative error is acceptable for the application's values?

What a Strong Answer Covers Guidance

  • Binary representation error and distinct subtraction results.
  • The effect of casting to float without modifying a or b.
  • Domain-based tolerance versus exact decimal arithmetic.

Follow-up Questions Guidance

  • Why is constructing a decimal object directly from a binary floating-point value risky?
  • When can a relative tolerance alone fail?