Làm thế nào để làm tròn số thập phân thứ n thành 2 trong java? (How can you round doubles to the nth decimal?)



Trong việc tính toán ta thường gặp phải các số thập phân có thứ phân là n ví như là 3.163811122222222, và tất nhiên ta không để con số như vậy để trình bày hoặc tính toán tiếp mà ta cần phải làm tròn nó.




Trong bài viết này tôi sẽ hướng dẫn một phương pháp đơn giản để làm tron số thập phân thứ n trong ngôn ngữ lập trình Java.

------------
/**
 * @(#)JavaRoundDouble.java
 *
 * JavaRoundDouble application
 *
 * @author developer.bnson@gmail.com
 * @web vnlives.net
 * @version 1.00 2014/4/3
 */

import java.text.DecimalFormat;

public class JavaRoundDouble {
   
    public static void main(String[] args) {
       
        double d1 = 0;
        double d2 = 9.49999;
        double d3 = 7.14159265359;
        double d4 = 99.5555555;
       
        //the number of zeros indicate the number of decimals.
        d1 = (double)Math.round(d1 * 100) / 100;
        d2 = (double)Math.round(d2 * 100) / 100;
        d3 = (double)Math.round(d3 * 100) / 100;
        d4 = (double)Math.round(d4 * 100) / 100;
       
        //the number of .0's indicate right padding.
        DecimalFormat df = new DecimalFormat("0.00");
        System.out.println(df.format(d1));
        System.out.println(df.format(d2));
        System.out.println(df.format(d3));
        System.out.println(df.format(d4));

    }
}
-----------

Kết quả sau khi thực thi ứng dụng ta nhân được sẽ là:













No comments:

Post a Comment