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

Page 1 of 1

## 3 Replies - 393 Views - Last Post: 05 October 2012 - 10:00 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=294478&amp;s=4d3b96640ff6fa328723fc496ad3b232&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 rneild

Reputation: 0
• Posts: 9
• 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;
//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
// 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

Reputation: 0
• 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.

### #3 accexpert

Reputation: 0
• 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

### #4 Biscuit Tickler

Reputation: 0
• 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;

```