59

In my printf, I need to use %f but I'm not sure how to truncate to 2 decimal places:

Example: getting

3.14159

to print as:

3.14

Arnaud
  • 6,339
  • 8
  • 47
  • 64
jmasterx
  • 47,653
  • 87
  • 281
  • 523

8 Answers8

101

Use this:

printf ("%.2f", 3.14159);
Kevin
  • 23,123
  • 15
  • 92
  • 146
15

You can use something like this:

printf("%.2f", number);

If you need to use the string for something other than printing out, use the NumberFormat class:

NumberFormat formatter = new DecimalFormatter("#.##");
String s = formatter.format(3.14159265); // Creates a string containing "3.14"
Alexis King
  • 40,717
  • 14
  • 119
  • 194
12
System.out.printf("%.2f", number);

BUT, this will round the number to the nearest decimal point you have mentioned.(As in your case you will get 3.14 since rounding 3.14159 to 2 decimal points will be 3.14)

Since the function printf will round the numbers the answers for some other numbers may look like this,

System.out.printf("%.2f", 3.14136); -> 3.14
System.out.printf("%.2f", 3.14536); -> 3.15
System.out.printf("%.2f", 3.14836); -> 3.15

If you just need to cutoff the decimal numbers and limit it to a k decimal numbers without rounding,

lets say k = 2.

System.out.printf("%.2f", 3.14136 - 0.005); -> 3.14
System.out.printf("%.2f", 3.14536 - 0.005); -> 3.14
System.out.printf("%.2f", 3.14836 - 0.005); -> 3.14
prime
  • 11,246
  • 11
  • 75
  • 112
4

Try:

printf("%.2f", 3.14159);

Reference:

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

Bill
  • 824
  • 6
  • 21
3

Use this

printf ("%.2f", 3.14159);
Jens Erat
  • 33,889
  • 16
  • 73
  • 90
Sibbs Gambling
  • 16,478
  • 33
  • 87
  • 161
3

as described in Formatter class, you need to declare precision. %.2f in your case.

Michał Šrajer
  • 27,013
  • 6
  • 52
  • 75
1

I suggest to learn it with printf because for many cases this will be sufficient for your needs and you won't need to create other objects.

double d = 3.14159;     
printf ("%.2f", d);

But if you need rounding please refer to this post

https://stackoverflow.com/a/153785/2815227

Community
  • 1
  • 1
mcvkr
  • 1,907
  • 3
  • 28
  • 50
1

You can try printf("%.2f", [double]);

Lior Ohana
  • 3,277
  • 3
  • 31
  • 46