新增 BigDecimals#toPlainString

dev
ZhouXY108 2024-10-11 17:11:56 +08:00
parent b72fd59b46
commit de0a732616
2 changed files with 65 additions and 0 deletions

View File

@ -3,6 +3,7 @@ package xyz.zhouxy.plusone.commons.util;
import java.math.BigDecimal;
import java.math.RoundingMode;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.base.Preconditions;
@ -39,6 +40,53 @@ public class BigDecimals {
return (StringTools.isNotBlank(val)) ? new BigDecimal(val) : ZERO;
}
/**
*
*/
private static final int DEFAULT_STR_SCALE = 2;
private static final RoundingMode DEFAULT_STR_ROUNDING_MODE = RoundingMode.HALF_UP;
/**
* 使{@link RoundingMode#HALF_UP}
*/
public static String toPlainString(@Nonnull BigDecimal value) {
AssertTools.checkParameterNotNull("value", value);
return toPlainStringInternal(value, DEFAULT_STR_SCALE, DEFAULT_STR_ROUNDING_MODE);
}
/**
* 使{@link RoundingMode#HALF_UP}
*/
public static String toPlainString(@Nonnull BigDecimal value, int scale) {
AssertTools.checkParameterNotNull("value", value);
return toPlainStringInternal(value, scale, DEFAULT_STR_ROUNDING_MODE);
}
/**
* 使 {@link RoundingMode}
*/
public static String toPlainString(@Nonnull BigDecimal value, @Nonnull RoundingMode roundingMode) {
AssertTools.checkParameterNotNull("value", value);
AssertTools.checkParameterNotNull("rounding mode", roundingMode);
return toPlainStringInternal(value, DEFAULT_STR_SCALE, roundingMode);
}
/**
* 使 {@link RoundingMode}
*/
public static String toPlainString(@Nonnull BigDecimal value,
int scale, @Nonnull RoundingMode roundingMode) {
AssertTools.checkParameterNotNull("value", value);
AssertTools.checkParameterNotNull("rounding mode", roundingMode);
return toPlainStringInternal(value, scale, roundingMode);
}
private static String toPlainStringInternal(@Nonnull BigDecimal value,
int scale, @Nonnull RoundingMode roundingMode) {
return value.setScale(scale, roundingMode).toPlainString();
}
/**
*
*/

View File

@ -0,0 +1,17 @@
package xyz.zhouxy.plusone.commons.util;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class BigDecimalsTests {
@Test
void testToPlainString() {
assertEquals("8.09", BigDecimals.toPlainString(BigDecimals.of("8.090")));
assertEquals("8.09", BigDecimals.toPlainString(BigDecimals.of("8.094")));
assertEquals("8.10", BigDecimals.toPlainString(BigDecimals.of("8.095")));
assertEquals("8.10", BigDecimals.toPlainString(BigDecimals.of("8.096")));
assertEquals("8.10", BigDecimals.toPlainString(BigDecimals.of("8.100")));
}
}