Friday, November 23, 2007

Rounding large values and eliminating exponentials

  1. For a requirement (where input is passed as Double and output as String) like


1 Should be rounded to dollars. No decimals, even if user enters.
2. Exponentials should not be displayed

3. Have amount returned as String in US format with dollar symbol and comma seperated


public class Test {

public static void main(String[] args){
System.out.println("Result : " + toUSCurrencyFormat(Double.parseDouble ("1000000000000123.123")));
}

public static String toUSCurrencyFormat(Double amount){

if(amount!=null&&!(ApplicationConstants.COMMON_EMPTYSTRING).equals(amount.toString())) {

Long l=Math.round(amount);
amount=Double.parseDouble(l.toString());
System.out.println("Rounded Value: " + Double.parseDouble(l.toString()));
NumberFormat usNF = DecimalFormat.getInstance(new Locale("en","US",""));
return usNF.format(amount);
}
return null;
}
}

3.

public static String toUSCurrencyFormatWithDollar(Double amount){

if(amount!=null && !(ApplicationConstants.COMMON_EMPTYSTRING).equals(amount.toString())){

Long l=Math.round(amount);

amount=Double.parseDouble(l.toString());

NumberFormat n = NumberFormat.getCurrencyInstance(java.util.Locale.US);

return n.format(amount);

}

return null;

}

0 Comments:

Post a Comment

<< Home