In a previous post, “.NET 11 Release Candidate - Breaking Change - Numeric Conversion Rounding”, we looked at a breaking change in .NET where float conversions to decimal were first taken to the nearest approximation before conversion.

As a recap, the prior behaviour in .NET 10 and earlier was this:

preservedDecimal

And the new behaviour in .NET 11 was this:

approximatedDecimal

I got to wondering how Java handles this.

The code is as follows:

void main() {
  // Declare a float type, a very truncated pi
  var pi = 3.14f;

  // Convert to BigDecimal and print
  IO.println(BigDecimal.valueOf(pi));
}

The equivalent of Decimal in Java is BigDecimal.

The code runs as follows:

javaConversion

It would seem that Java already has this behaviour.

TLDR

Java already approximates float values prior to conversion.

Happy hacking!