javaspring-bootnumberformatter

Decimal separator in long (Java/Spring)


I need to put the decimal separator point in a Long, I have tried in several ways, but I need it to be dynamic since the decimal separator can change, I have tried with DecimalFormat format = new DecimalFormat("###.##"); but this is not dynamic and it doesn't work the way I wanted it to

Example 1

long amount = 123456;

int decimal = 2;

The result should be Double newAmount = 1234.56

Example 2

long amount = 123456;

int decimal = 4;

The result should be Double newAmount = 12.3456


Solution

  • If I understand correctly, this is what you are trying to achieve:

    Long amount = 123456;
    int decimal = 2;
    double newAmount = amount.doubleValue();
    newAmount = newAmount / Math.pow(10, decimal);
    

    Use the pow method of java.lang.math to calculate the power of a number.

    Be careful to declare your variable as an object of type Long and not a primitive type if you want to use one of its functions.

    As suggested, it is even simpler to just use a double variable instead of a long from the start:

    double amount = 123456;
    int decimal = 2;
    amount = amount / Math.pow(10, decimal);