ankushbbbr
ankushbbbr

Reputation: 923

passing a value to float format specifier in java

to round a number to n-decimal places, in C, I use the following method:-

#include <stdio.h>          
void main()    
{    
float a=0.12685;      
int n=3;     
printf("%.*f",n,a);    
}       

NOTE:- only '*' can be used to pass a value to the float format specifier. statements like %.xf give error.

Is there a way to do the same thing in Java?

Upvotes: 0

Views: 279

Answers (2)

Andreas
Andreas

Reputation: 159260

You could just build the format string:

double a = 0.12685;
int n = 3;
System.out.printf("%." + n + "f", a);

You can also use a NumberFormat:

NumberFormat fmt = NumberFormat.getInstance();
fmt.setMinimumFractionDigits(n);
fmt.setMaximumFractionDigits(n);
System.out.print(fmt.format(a));

Both will print:

0.127

Upvotes: 2

SMA
SMA

Reputation: 37103

If you want your float value to round to 3 decimal places then you could work like:

float a = 0.12685f;
System.out.printf("%.3f", a);
//Output:
0.127

Better way would be to use formatter like:

DecimalFormat df = new DecimalFormat("#.000");
System.out.println(df.format(a));
//output
0.127

Upvotes: 0

Related Questions