小数点后的零添加正数 [英] adding n number of zeros after decimal

查看:183
本文介绍了小数点后的零添加正数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要给用户,直到数位输入的数字精度。就像如果用户输入一些随机值,并给出他想要的精度,直到三个数字,然后我需要四舍五入的数字,直到小数点后三位。所以我做了这样的事情。

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 round off the digit till three places after decimal. So i did something like this

 int index = value.indexOf('.'); 
            if (index >= 0)
            {
                String fractional = value.substring(index);

                if (fractional.length() > decimalPlaces)
                {
                    floatValue = roundOffDecimals(floatValue, decimalPlaces);
                }
            }
            retVal = new Float(floatValue);

但是,当用户输入一些价值,但不进入为十进制我需要显示它作为零小数位数的惨淡值的值。
像15是他的电话号码和3个是他的准确性,然后我需要显示号码15.000

but when user enters some value but do not enters any value as decimal I need to display it as dismal value with zeros as number of decimal places. like for 15 is his number and 3 is his accuracy then I need to display number as 15.000

我不能够小数点后显示为零时,它总是变化。请帮忙。
我试图DeciamlFormat DF =新DecimalFormat的(,###);但需要静态值。而我的精度不断变化。

I am not able to display zero after decimal when it always changes. Please help. I tried DeciamlFormat df = new DecimalFormat("",#.##); but takes static value. And my accuracy keeps changing.

任何帮助将AP preciated。

Any help will be appreciated.

推荐答案

您可以创建一个返回您小数的确切格式的方法。下面是一个例子:

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());
}

这篇关于小数点后的零添加正数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆