Wednesday, March 26, 2014

Eliminate "E" from the amount string to show only the amount without "E" (8.23452345678E9 as 8234523456.78)

 Normally a beginner in development will end up storing the amount in Double variable which will eventually store in "E" format (for ex., 8.23452345678E9) and when we deal with XML's we end up sending the same value to the XML Tag, hence rendering in a front end would be similar which is not suitable for a user to view. Hence this situation has to be avoided.

First resolution would be "Try avoiding usage of Double variables for amount fields instead use BigDecimal" if you have option to do that.

What if the above change is something which is not in your hands (may be because of many reasons like its being used at many places I cannot change the return type of the function, its a third party webservice it is giving like that I cannot change it etc.,)? 

You basically have to convert this amount which is in the above mentioned format into a BigDecimal format and eventually update the xml tag with the value that you have converted.

This can be done as below

String amountInString="8.23452345678E9";
System.out.println(String.valueOf(BigDecimal.valueOf(Double.valueOf(amountInString))));

Courtesy : Learnings from GIB Project
________________________________________________________________________________
Continuation based on Comments :

If you do not want to get this E format itself then you can follow the below :

String str= "2000100010.1245" ;
BigDecimal bg=new BigDecimal(str);
System.out.println(bg.toString());

if the decimal value has to be restricted to only two digits after decimal then we can use Scale method :

System.out.println(bg.setScale(2, RoundingMode.CEILING));

Result : 2000100010.13

If any calculations have to be made with such large numbers then big decimal has Add,subtract etc methods

1 comment:

  1. If you do not want to get this E format itself then you can follow the below :

    String str= "2000100010.1245" ;
    BigDecimal bg=new BigDecimal(str);
    System.out.println(bg.toString());

    if the decimal value has to be restricted to only two digits after decimal then we can use Scale method :

    System.out.println(bg.setScale(2, RoundingMode.CEILING));

    Result : 2000100010.13
    If any calculations have to be made with such large numbers then big decimal has Add,subtract etc methods

    ReplyDelete