Search code examples
javabigdecimal

Concatenate two numbers


How do I concatenate two numbers in BigDecimal? I have this example:

BigDecimal d = BigDecimal.valueOf(5.5);
        int a = 1;
        int b = 11;

and I want to concat d.a and d.b to generate 5.501 and 5.511 in same length without using divide or other operation!

Is there an instruction with BigDecimal to make it directly ?


Solution

  • Use the fact that BigDecimal can parse stings, and that strings are easy to concatenate.

    BigDecimal d = BigDecimal.valueOf(5.5);
    int a = 1;
    int b = 11;
    
    BigDecimal da = new BigDecimal(String.format("%s%02d", d, a));
    BigDecimal db = new BigDecimal(String.format("%s%02d", d, b));
    
    System.out.println(da);
    System.out.println(db);
    

    Output:

    5.501
    5.511
    

    The length is hard coded in %02d. You could generate the format string dynamically by inspecting String.valueOf(a).length().