adding n number of zeros after decimal

前端 未结 3 378
猫巷女王i
猫巷女王i 2020-12-20 02:06

I need to give accuracy of a number entered by user till few digit. like if user enter some random value and gives that he wants accuracy till three digit then I need to rou

3条回答
  •  死守一世寂寞
    2020-12-20 02:47

    You can create a method that returns the exact format for your decimals. Here is an example:

    public String formatNumber(int decimals, double number) {
        StringBuilder sb = new StringBuilder(decimals + 2);
        sb.append("#.");
        for(int i = 0; i < decimals; i++) {
            sb.append("0");
        }
        return new DecimalFormat(sb.toString()).format(number);
    }
    

    If you don't need to change the decimals value so often, then you can change your method to something like:

    public DecimalFormat getDecimalFormat(int decimals) {
        StringBuilder sb = new StringBuilder(decimals + 2);
        sb.append("#.");
        for(int i = 0; i < decimals; i++) {
            sb.append("0");
        }
        return new DecimalFormat(sb.toString());
    }
    

提交回复
热议问题