Results 1 to 4 of 4
  1. #1
    Join Date
    Nov 2012
    Posts
    13
    Rep Power
    0

    Default Round to 2 decimal places.

    Working on one of my first Java programs and I am attempting to write a program that asks for mass in kg and outputs mass in pounds rounded to 2 decimal places and I am stuck. I have gotten it to work except I cant seem to figure out how to round it off, here is what I have so far:

    import java.util.*;
    import java.io.*;

    public class Evaluate_2
    {
    public static void main (String[] args) throws IOException
    {
    Scanner in = new Scanner(System.in);

    double weight_in_kilograms;

    double weight_in_pounds;

    System.out.println("Enter your mass in kilograms");

    weight_in_kilograms = in.nextDouble();

    weight_in_pounds = weight_in_kilograms*2.2;

    System.out.println("Your mass in pounds is"+ weight_in_pounds);
    }
    }

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Round to 2 decimal places.

    You will want to round the String representation of the number you'll display, and for that look into using either a DecimalFormat object or printing out your data using System.out.printf in place of your System.out.println.

  3. #3
    Join Date
    Nov 2012
    Posts
    13
    Rep Power
    0

    Default Re: Round to 2 decimal places.

    thank you for the info, i incorporated that into my code and it does work but it will only output 2 decimal places if the result is not an integer. I used the DecimalFormat object

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,450
    Rep Power
    18

    Default Re: Round to 2 decimal places.

    The result is not an integer.
    'weight_in_pounds' is a double.

    Do you mean you want it to pad to 2 decimal places?
    eg 20.00
    Then the API for DecimalFormat explains how to do this.
    Please do not ask for code as refusal often offends.

Similar Threads

  1. round to two decimal places
    By javaMike in forum New To Java
    Replies: 3
    Last Post: 12-24-2011, 02:01 AM
  2. Replies: 0
    Last Post: 02-06-2011, 09:29 PM
  3. 3 Decimal Places
    By benhawk in forum New To Java
    Replies: 7
    Last Post: 11-02-2010, 09:28 PM
  4. Replies: 4
    Last Post: 01-16-2009, 06:17 PM
  5. numbers with two decimal places
    By little_polarbear in forum New To Java
    Replies: 8
    Last Post: 08-27-2008, 11:04 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •