In Java how do you convert a decimal number to base 36?

后端 未结 11 1453
粉色の甜心
粉色の甜心 2020-11-29 04:55

If I have a decimal number, how do I convert it to base 36 in Java?

11条回答
  •  Happy的楠姐
    2020-11-29 05:50

    I got this code from this website in JavaScript, and this is my version in java:

    public static String customBase (int N, String base) {
    
        int radix = base.length();
    
        String returns = "";
    
        int Q = (int) Math.floor(Math.abs(N));
        int R = 0;
    
        while (Q != 0) {
    
            R = Q % radix;
            returns = base.charAt(R) + returns;
            Q /= radix; 
    
        }
    
        if(N == 0) {
            return String.valueOf(base.toCharArray()[0]);
        }
    
        return  N < 0 ? "-" + returns : returns;
    
    }
    

    This supports negative numbers and custom bases.

    Decimal Addon:

    public static String customBase (double N, String base) {
    
        String num = (String.valueOf(N));
        String[] split = num.split("\\.");
        if(split[0] == "" || split[1] == "") {
            return "";
        }
        return customBase(Integer.parseInt(split[0]), base)+ "." + customBase(Integer.parseInt(split[1]), base);
    
    }
    

提交回复
热议问题