3 Replies - 2225 Views - Last Post: 05 October 2012 - 10:00 PM Rate Topic: -----

#1 rneild  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 05-October 12

New to Java: Trying to truncate a double from 15 decimal places to 2

Posted 05 October 2012 - 08:47 PM

Hello
I'm new to this forum,hope that my code will display below. I am doing my first program with scanners and converting values, i started off with integers but that was not realistic so i changed to double however the output
		import java.util.Scanner;
public class Milestokm {
	public static void main(String[] args) {
                //Converting Miles to Kilometers
		final double MILES_TO_KM = 1.60935;
		double answer;
		//Scanner to creates method to read input
		Scanner scan = new Scanner(System.in);
		double miles;
		//Input
		System.out.println("Enter the number of miles:");
		miles = scan.nextDouble();		
		// calculate Miles to KM
		answer = miles * MILES_TO_KM;
		// output
		System.out.println("The number of miles: " +miles+ " M converted to kilometers = " + answer +"km");



the output shows way too many decimal places, is there an simple way of getting 2 decimal places?

Is This A Good Question/Topic? 0
  • +

Replies To: New to Java: Trying to truncate a double from 15 decimal places to 2

#2 Jakey  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 29-September 12

Re: New to Java: Trying to truncate a double from 15 decimal places to 2

Posted 05 October 2012 - 08:56 PM

You can use printf, which stands for print format, instead of println at the end of your code.

There are a couple different things to use in printf that I know you will need.

%s reserves spaces needed for characters
%.2f sets floating point numbers to 2 digits after the decimal
/n creates a new line

I am also new to coding and hope that this helps point you in the correct direction.
Was This Post Helpful? 0
  • +
  • -

#3 accexpert  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 05-October 12

Re: New to Java: Trying to truncate a double from 15 decimal places to 2

Posted 05 October 2012 - 09:20 PM

Hi,

Try this:
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
System.out.println(nf.format(a));


This will show you only 2 digits.

Chris
Was This Post Helpful? 0
  • +
  • -

#4 Biscuit Tickler  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 01-October 12

Re: New to Java: Trying to truncate a double from 15 decimal places to 2

Posted 05 October 2012 - 10:00 PM

The users above me are correct but I use Math.round(); I guess I just find it easier because I have used it so much. For example:
double x = 14.23424242;
double newx = Math.round(x*100.0)/100.0;


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1