Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format float to maximum N decimal places

I'd like to format a number to maximum N decimal places. There's another similar and popular question here, but that's not exactly what I'm looking for.

I'm looking for something like this, let's say I want max. 2 places, so this would be:

1.00  -> "1"    (not "1.00")
1.20  -> "1.2"  (not "1.20")
1.23  -> "1.23"
1.234 -> "1.23"
1.235 -> "1.24"

The difference to the other question is that I don't want trailing zeros behind the comma if I don't need them.

I'd like to know whether this is doable with String.format(), not with Math.round(), or DecimalFormat. The other question shown above provides a solution with DecimalFormat.

The answer does not need to be variable given N as an argument. I just chose N as an example.

like image 753
mac Avatar asked May 13 '16 00:05

mac


People also ask

How do I set a float limit?

Use round() to limit a float to two decimal places Call round(number, ndigits) with a float as number and 2 as ndigits to round the float to two decimal places.

How do you format a float upto 2 decimal places?

The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).


3 Answers

You can use DecimalFormat.

Quoting the documentation:

You can use the DecimalFormat class to format decimal numbers into locale-specific strings. This class allows you to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator.

The pound sign (#) denotes a digit and the period is a placeholder for the decimal separator.

public void test(){
    DecimalFormat df = new DecimalFormat("#.##");
    System.out.println(df.format(1.00));
    System.out.println(df.format(1.20));
    System.out.println(df.format(1.23));
    System.out.println(df.format(1.234));
    System.out.println(df.format(1.235));
}

Output:

1
1.2
1.23
1.23
1.24

Update: since you updated the question and you wanted to use String.format, searching in SO found this thread and leverage a trick plus regex. So, you could use something like this:

public static void main (String[] args) throws java.lang.Exception
{
    System.out.println(fmt(1.00));
    System.out.println(fmt(1.20));
    System.out.println(fmt(1.23));
    System.out.println(fmt(1.234));
    System.out.println(fmt(1.235));
}

public static String fmt(double d)
{
    if(d == (long) d)
        return String.format("%d",(long)d);
    else
        return String.format("%.2f",d).replaceAll("0*$", "");
}

The output is:

1
1.2
1.23
1.23
1.24

Anyway, I would use DecimalFormat instead.

like image 115
Federico Piazza Avatar answered Sep 28 '22 03:09

Federico Piazza


You can also control the formatting of DecimalFormat using setMaximumFractionDigits(...) like so:

double d = 1.234567;
DecimalFormat df = new DecimalFormat();
for (int i = 2; i < 6; ++i) {
  df.setMaximumFractionDigits(i);
  System.out.println(df.format(d));
}

This might be better for your use case than generating a format using StringBuilder or similar.

like image 36
clstrfsck Avatar answered Sep 28 '22 03:09

clstrfsck


Use NumberFormat.

NumberFormat format = NumberFormat.getInstance();
format.setMaximumFractionDigits(2); // or N

System.out.println(format.format(1)); // -> 1
System.out.println(format.format(1.2)); // -> 1.2
System.out.println(format.format(1.23)); // -> 1.23
System.out.println(format.format(1.234)); // -> 1.23
System.out.println(format.format(1.235)); // -> 1.24

NumberFormat also works with Locales and you can change the rounding mode.

NumberFormat format = NumberFormat.getInstance(Locale.GERMANY);
format.setMaximumFractionDigits(2);
format.setRoundingMode(RoundingMode.CEILING);

System.out.println(format.format(1)); // -> 1
System.out.println(format.format(1.2)); // -> 1,2
System.out.println(format.format(1.23)); // -> 1,23
System.out.println(format.format(1.234)); // -> 1,24
System.out.println(format.format(1.235)); // -> 1,24
like image 33
Matthias Gerth Avatar answered Sep 28 '22 03:09

Matthias Gerth