Format printing of floats?

by BobG » Sat, 06 Mar 2010 23:18:53 GMT

Sponsored Links
 What shows: 1.23456789
What I want: 1.23
In c it would be printf("%4.2f",n);
In Java its? (I dont know yet).


Format printing of floats?

by Kitzy » Sun, 07 Mar 2010 23:57:46 GMT

 Look up DecimalFormat
You'll need to create the format on that object:
String pattern = "0.##"; // or "0.00" depending if you want 1.5 to
show a 1.5 or 1.50
DecimalFormat my_formatter = new DecimalFormat (pattern);
String formatted_string = my_formatter.format (1.23456789)

You could put the pattern directly into the constructor to only take 2
lines of code instead of 3.



Sponsored Links

Format printing of floats?

by Scott Marlowe » Wed, 10 Mar 2010 04:32:50 GMT

 I don't know about the Java printf equivalent, but this function will
return a double with only the specified number of decimal places. You
should be able to modify with a "return bd.toString" or simplify in
some other way to satisfy your needs.

private static double round(double d, int decimalPlace)
        BigDecimal bd = new BigDecimal(Double.toString(d));
        bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();


Other Threads

1. Android listview with pre selected checkboxes

You can create your own ListAdapter and then override the getViews
method to setup the checkboxes similar to this:

/* (non-Javadoc)
         * @see android.widget.Adapter#getView(int, android.view.View,
        public View getView(int position, View convertView, ViewGroup parent)
                Setup setup = (Setup)this.getItem(position);
                if (convertView == null)
            convertView = inflater.inflate(R.layout.setup_mgt_row,

                TextView textView = (TextView) convertView.findViewById

                ImageView selectedView = (ImageView) convertView.findViewById
                        selectedView.setImageState(new int[]
{ android.R.attr.state_checked }, true);
                        selectedView.setImageState(new int[]
{ android.R.attr.state_empty }, true);

                ImageView deleteView = (ImageView)convertView.findViewById

        return convertView;



2. setBuiltInZoomControls - android tutorial

new in android - and starting to play with the tutorial's.
i tried the helloMap - and the map is going up nicely - but when im
adding this:

where mapView is a  findViewbyId(;

it doesn't work. -- i get an error STOPPED UNEXPECTEDLY...

any suggestions?

im coping the code 1by1 from the toturial , including the layout file
and manifest
(as i said - without the zoom cntrol - it works fine)


3. Load Imageview from Internet in Background

4. FLV - VP6 integration

5. View objects lose onclick listeners when screen orientation changes

6. ada yg bisa bantu g ya??

7. Problem with 9-patches in <selector> drawable for custom button style