0

this is my first entry to stackoverflow so please let me know if something is wrong.

I know how to show an imported float number with x decimal numbers. But how do you define the amount of decimal numbers via a new scanned int number?

This is my code: (of course "%.decimalf" doesn't work, I just wanted to test it)

anyone? thanks in advance!

import java.util.Scanner;

public class Fliesskommazahl{

  public static void main (String[] args){

    // ask for/import floating point number
    System.out.println("Please enter a floating point number like 1,1234: ");
    Scanner scanner = new Scanner(System.in);
    float number = scanner.nextFloat();

    // show floating point number
    System.out.println("You've entered: " + number);

    /* show number with exactly two decimal places
       In short, the %.02f syntax tells Java to return your variable (number) with 2 decimal places (.2)
       in decimal representation of a floating-point number (f) from the start of the format specifier (%).
    */
    System.out.println("Your number with two decimal places: ");
    System.out.printf("%.02f", number);
    System.out.println();

    // import second (positive) number.
    System.out.println("Please enter a positive integer number to define amount of decimal places: ");
    Scanner scanner2 = new Scanner(System.in);
    int decimal = scanner.nextInt();

    // show imported floating point number with imported number of decimal places.

    System.out.printf("%.decimalf", number);



  }
}
Phewz
  • 3
  • 1
  • 6
  • 3
    Possible duplicate of [Print Integer with 2 decimal places in Java](http://stackoverflow.com/questions/12990451/print-integer-with-2-decimal-places-in-java) – Mage Xy Oct 07 '15 at 18:04

2 Answers2

1

This could work

System.out.printf ("%." + decimal + "f", number);
amicngh
  • 7,831
  • 3
  • 35
  • 54
Alberto Saito
  • 271
  • 1
  • 6
0

You should use this class I think this could work out really good for you here it is:

double num = 123.123123123;
DecimalFormat df = new DecimalFormat("#.000");
System.out.println(df.format(num));

In this case the output would be 123,123, the amount of zeros after the #. is the amount of numbers you want after the dot.

  • it's important to import the amount of decimal places. but thanks! I will keep this in mind for future :) – Phewz Oct 07 '15 at 19:56