Java NumberFormat setRoundingMode()方法及示例

Java NumberFormat setRoundingMode()方法及示例

setRoundingMode() 方法是java.text.NumberFormat的一个内置方法,用于设置该NumberFormat中使用的RoundingMode。处理不同舍入模式的子类应覆盖此方法。

语法

public void setRoundingMode(RoundingMode mode)

参数 :该函数接受一个强制性参数 mode ,它指定了要设置的模式。

返回值 :该函数不返回任何东西,因此它的返回类型为void。

异常: 该函数抛出两个异常,描述如下。

  • UnsupportedOperationException :如果默认实现总是抛出这个异常。
  • NullPointerException :如果roundingMode是空的。

下面是上述函数的实现。

程序1 :

// Java program to implement
// the above function
 
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Currency;
import java.math.RoundingMode;
 
public class Main {
    public static void main(String[] args)
        throws Exception
    {
 
        NumberFormat nF
            = NumberFormat.getNumberInstance();
 
        System.out.println("set initially as: "
                           + nF.getRoundingMode());
 
        // Set grouping
        nF.setRoundingMode(RoundingMode.FLOOR);
 
        // Print the final
        System.out.println("set finally as: "
                           + nF.getRoundingMode());
    }
}

输出

set initially as: HALF_EVEN
set finally as: FLOOR

程序2

// Java program to implement
// the above function
 
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Currency;
import java.math.RoundingMode;
 
public class Main {
    public static void main(String[] args)
        throws Exception
    {
 
        NumberFormat nF
            = NumberFormat.getNumberInstance();
 
        System.out.println("set initially as: "
                           + nF.getRoundingMode());
 
        // Set grouping
        nF.setRoundingMode(RoundingMode.DOWN);
 
        // Print the final
        System.out.println("set finally as: "
                           + nF.getRoundingMode());
    }
}

输出

set initially as: HALF_EVEN
set finally as: DOWN

程序3

// Java program to implement
// the above function
 
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Currency;
import java.math.RoundingMode;
 
public class Main {
    public static void main(String[] args)
        throws Exception
    {
        try {
 
            NumberFormat nF
                = NumberFormat.getNumberInstance();
 
            System.out.println("set initially as: "
                               + nF.getRoundingMode());
 
            // Set grouping
            nF.setRoundingMode(null);
 
            // Print the final
            System.out.println("set finally as: "
                               + nF.getRoundingMode());
        }
        catch (Exception e) {
            System.out.println("Exception is: "
                               + e);
        }
    }
}

输出

set initially as: HALF_EVEN
Exception is: java.lang.NullPointerException

参考资料 : https://docs.oracle.com/javase/10/docs/api/java/math/RoundingMode.html

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程