adding n number of zeros after decimal

前端 未结 3 375
猫巷女王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:33

    You can indeed use NumberFormat to do this

    double amount = 15;
    NumberFormat formatter = new DecimalFormat("#0.000");
    System.out.println("The Decimal Value is:"+formatter.format(amount));
    
    0 讨论(0)
  • 2020-12-20 02:36

    you can use string format:

    Double area = 6

    String ar = String.format("%.3f", area); ar = 6.000

    0 讨论(0)
  • 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());
    }
    
    0 讨论(0)
提交回复
热议问题