Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions src/java.base/share/classes/java/math/BigDecimal.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@

import jdk.internal.access.JavaLangAccess;
import jdk.internal.access.SharedSecrets;
import jdk.internal.math.FormattedFPDecimal;
import jdk.internal.util.DecimalDigits;

/**
Expand Down Expand Up @@ -1393,11 +1394,18 @@ static BigDecimal zeroValueOf(int scale) {
* @since 1.5
*/
public static BigDecimal valueOf(double val) {
// Reminder: a zero double returns '0.0', so we cannot fastpath
// to use the constant ZERO. This might be important enough to
// justify a factory approach, a cache, or a few private
// constants, later.
return new BigDecimal(Double.toString(val));
if (!Double.isFinite(val)) {
throw new NumberFormatException("Infinite or NaN");
}

var fmt = FormattedFPDecimal.valueForDoubleToString(Math.abs(val));
long s = fmt.getSignificand();
if (val < 0) {
// Original s is never negative, so no overflow
s = -s;
}

return valueOf(s, -fmt.getExp(), fmt.getPrecision());
}

// Arithmetic Operations
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
Expand Down Expand Up @@ -57,8 +57,7 @@ private FormattedFPDecimal() {
}

public static FormattedFPDecimal valueOf(double v, int prec, char form) {
FormattedFPDecimal fd = new FormattedFPDecimal();
DoubleToDecimal.split(v, fd);
FormattedFPDecimal fd = split(v);
return switch (form) {
case SCIENTIFIC -> fd.scientific(prec);
case PLAIN -> fd.plain(prec);
Expand All @@ -69,6 +68,74 @@ public static FormattedFPDecimal valueOf(double v, int prec, char form) {
};
}

private static FormattedFPDecimal split(double v) {
FormattedFPDecimal fd = new FormattedFPDecimal();
DoubleToDecimal.split(v, fd);
return fd;
}

/**
* Returns a FormattedFPDecimal with the appropriate precision for
* {@link Double#toString(double)}.
*
* @see java.math.BigDecimal#valueOf(double)
*/
public static FormattedFPDecimal valueForDoubleToString(double v) {
final FormattedFPDecimal fd = split(v);
final int expR = fd.getExponentRounded();

// Adjust precision, following rules for Double.toString. There is
// always at least one digit and some cases require an extra one to
// force a digit after the decimal. No additional rounding is performed;
// no significant trailing digits are removed.

final int targetPrec =
// No extra trailing digit needed
(-3 <= expR && expR < 0) ? 1

// Keep digits to left of decimal, plus leave a trailing zero
: (0 <= expR && expR < 7) ? expR + 2 :

// Otherwise, require at least 2 digits, to include trailing
// digit when there is a single digit
2;


long s = fd.f;
int prec = fd.n;

if (prec < targetPrec) {
// Add zeros needed to reach target precision
final int addZeros = targetPrec - prec;
s *= MathUtils.pow10(addZeros); // addZeros will be at most 8
prec = targetPrec;
} else {
// Remove trailing zeros to try to reach target precision
while (prec > targetPrec && s % 10 == 0) {
s = s / 10;
prec--;
}
}

// Calculate new e based on updated precision
final int eNew = expR - prec + 1; // expR is defined as prec + e - 1
fd.set(s, eNew, prec);

return fd;
}

public long getSignificand() {
return f;
}

public int getPrecision() {
return n;
}

public int getExp() {
return e;
}

public void set(long f, int e, int n) {
/* Initially, n = 0 if f = 0, and 10^{n-1} <= f < 10^n if f != 0 */
this.f = f;
Expand Down
74 changes: 74 additions & 0 deletions test/jdk/java/math/BigDecimal/ValueOfDouble.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/

/*
* @test
* @bug 8356709
* @summary Test Double.toString(double)
* @run junit ValueOfDouble
*/


import org.junit.jupiter.api.Test;

import java.math.BigDecimal;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;


public class ValueOfDouble {
private static final String DIGITS = "1234567000003456789"; // Enough digits to fill a long

@Test
public void testValueOfDouble() {
checkValue(0.0);
checkValue(-0.0);
checkValue(Math.PI);
checkValue(-Math.PI);
checkValue(Double.MAX_VALUE);
checkValue(Double.MIN_VALUE);
checkValue(1e-44); // Lots of digits with lots of 9s

for (int prec = 1; prec < DIGITS.length(); prec++) {
String prefix = DIGITS.substring(0, prec);
for (int exp = -30; exp < 30; exp++) {
double value = Double.parseDouble(prefix + "e" + exp);
checkValue(value);
checkValue(-value);
}
}
}

private static void checkValue(double value) {
BigDecimal expected = new BigDecimal(Double.toString(value));
assertEquals(expected, BigDecimal.valueOf(value));
}

@Test
public void testExceptions() {
assertThrows(NumberFormatException.class, () -> BigDecimal.valueOf(Double.NaN));
assertThrows(NumberFormatException.class, () -> BigDecimal.valueOf(Double.POSITIVE_INFINITY));
assertThrows(NumberFormatException.class, () -> BigDecimal.valueOf(Double.NEGATIVE_INFINITY));
}
}
21 changes: 20 additions & 1 deletion test/micro/org/openjdk/bench/java/math/BigDecimals.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
Expand Down Expand Up @@ -227,4 +227,23 @@ public void testCompareTo(Blackhole bh) {
bh.consume(c.compareTo(s));
}
}


/** Invokes the valueOf(double) of BigDecimal with various different values. */
@Benchmark
@OperationsPerInvocation(TEST_SIZE)
public void testValueOfWithDouble(Blackhole bh) {
for (double s : doubleInputs) {
bh.consume(BigDecimal.valueOf(s));
}
}

/** Create BigDecimal from double with Double.toString on different values. */
@Benchmark
@OperationsPerInvocation(TEST_SIZE)
public void testValueOfWithDoubleString(Blackhole bh) {
for (double s : doubleInputs) {
bh.consume(new BigDecimal(Double.toString(s)));
}
}
}