Created
January 12, 2021 10:04
-
-
Save AoEiuV020/be724846107b6522164e3dee9478428a to your computer and use it in GitHub Desktop.
java仿js的toString,无法解决精度问题,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Test | |
public void testRadix() { | |
assertEquals("0.o72tt3lcjtq", toString("0.6721285152844136", 36)); | |
} | |
public String toString(String number, int radix) { | |
BigDecimal N = new BigDecimal(number); | |
StringBuilder sb = new StringBuilder(); | |
BigInteger i = N.toBigInteger(); | |
sb.append(i.toString(radix)); | |
sb.append('.'); | |
while(new BigDecimal(N.intValue()).compareTo(N) != 0 && sb.length() < 13) { | |
N = N.multiply(new BigDecimal(radix)); | |
i = N.toBigInteger().mod(new BigDecimal(radix).toBigInteger()); | |
sb.append(i.toString(radix)); | |
} | |
return sb.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment