Thursday, 26 March 2020

Format float to n decimal places

Approach 1: Using String.format.
String result1 = String.format("%.2f", number);

Approach 2: Using NumberFormat.
NumberFormat formatter = NumberFormat.getInstance(Locale.US);
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
formatter.setRoundingMode(RoundingMode.HALF_UP);
Float result2 = new Float(formatter.format(number));

Approach 3: Using BigDecimal.
BigDecimal result3 = new BigDecimal(number).setScale(2, BigDecimal.ROUND_HALF_UP);

App.java
package com.sample.app;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Locale;

public class App {

    public static void main(String args[]) {
        float number = 10.23456f;

        String result1 = String.format("%.2f", number);

        NumberFormat formatter = NumberFormat.getInstance(Locale.US);
        formatter.setMaximumFractionDigits(2);
        formatter.setMinimumFractionDigits(2);
        formatter.setRoundingMode(RoundingMode.HALF_UP);
        Float result2 = new Float(formatter.format(number));

        BigDecimal result3 = new BigDecimal(number).setScale(2, BigDecimal.ROUND_HALF_UP);
        
        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);

    }

}

Output

10.23
10.23
10.23


You may like

No comments:

Post a Comment