Search code examples
javabigdecimal

Java BigDecimal long with decimal conversion


I have a BigDecimal value of 123.45. I'd like to convert it to a long value of 12345 and I wonder what's the best way of doing this.

I'd rather avoid doing something like val.multiply(new BigDecimal(100)).toBigInteger()


Solution

  • Just posting this in case you want to know. Made a test for performances, as expected String replacement performed the worst.

    results: movePointRight: 1230 multiply: 833 scaleByPowerOfTen: 591 String replacement: 3289

        BigDecimal val = new BigDecimal(0);
        long start = System.currentTimeMillis();
        for(int i = 0; i < 1000000; i++) {
            BigDecimal d = new BigDecimal(123.45);
            val = d.movePointRight(2);
        }
        long end = System.currentTimeMillis();
        System.out.println("movePointRight: " + (end - start));
    
        BigDecimal ten = new BigDecimal(10);
        start = System.currentTimeMillis();
        for(int i = 0; i < 1000000; i++) {
            BigDecimal d = new BigDecimal(123.45);
            val = d.multiply(new BigDecimal(100));
        }
    
        end = System.currentTimeMillis();
        System.out.println("multiply: " + (end - start));
    
        start = System.currentTimeMillis();
        for(int i = 0; i < 1000000; i++) {
            BigDecimal d = new BigDecimal(123.45);
            val = d.scaleByPowerOfTen(2);
        }
    
        start = System.currentTimeMillis();
        for(int i = 0; i < 1000000; i++) {
            BigDecimal d = new BigDecimal(123.45);
            val = d.scaleByPowerOfTen(2);
        }
        end = System.currentTimeMillis();
        System.out.println("scaleByPowerOfTen: " + (end - start));
    
        start = System.currentTimeMillis();
        for(int i = 0; i < 1000000; i++) {
            BigDecimal d = new BigDecimal(123.45);
            val =  new BigDecimal(d.toString().replace(".", ""));
        }
        end = System.currentTimeMillis();
        System.out.println("String replacement: " + (end - start));