Click to See Complete Forum and Search --> : displaying a float to 2 decimal places {Resolved} thanks
steve_rm
Nov 1st, 2003, 02:36 AM
Hello
I am using a float to give a anwer in dollars, but how can l display the currency to 2 decimal places.
e.g.
416.66
Thanks in advance
Dillinger4
Nov 1st, 2003, 11:06 PM
I guess you could do it like this.
import java.text.*;
import java.text.NumberFormat.Field;
public class F {
public static void main(String[] args) {
double d = 3.333333333333;
StringBuffer sb = new StringBuffer();
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.format(d, sb, new FieldPosition(Field.DECIMAL_SEPARATOR));
System.out.println(d);
System.out.println(sb);
}
}
Dillinger4
Nov 1st, 2003, 11:51 PM
Since you are working with currency i guess this would be a better snippet. :lol:
import java.text.*;
import java.util.Locale;
import java.text.NumberFormat;
import java.text.NumberFormat.Field;
public class F {
public static void main(String[] args) {
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
String field1 = args[0];
String field2 = args[1];
double d1 = formatPlaces(field1);
double d2 = formatPlaces(field2);
double temp = d1 + d2;
System.out.println(temp);
String s = nf.format(temp);
System.out.println(s);
}
public static double formatPlaces(String field){
StringBuffer sb = new StringBuffer();
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.format(Double.parseDouble(field), sb, new FieldPosition(Field.DECIMAL_SEPARATOR));
return Double.parseDouble(sb.toString());
}
}
Dillinger4
Nov 4th, 2003, 12:05 AM
:sick: sorry forgot the error handling.
import java.text.*;
import java.util.Locale;
import java.text.NumberFormat;
import java.text.NumberFormat.Field;
public class F {
public static void main(String[] args) {
try{
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
String field1 = args[0];
String field2 = args[1];
double d1 = formatPlaces(field1);
double d2 = formatPlaces(field2);
double temp = d1 + d2;
String s = nf.format(temp);
System.out.println(s);
}catch(Exception e){System.err.println(e);}
}
public static double formatPlaces(String field) throws NumberFormatException{
StringBuffer sb = new StringBuffer();
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.format(Double.parseDouble(field), sb, new FieldPosition(Field.DECIMAL_SEPARATOR));
return Double.parseDouble(sb.toString());
}
}
steve_rm
Nov 8th, 2003, 11:42 PM
Thanks for you help
Steve
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.