如何卸下“。0”;以十进制格式,并在java中将1.01转换为1

如何卸下“。0”;以十进制格式,并在java中将1.01转换为1,java,double,Java,Double,我的应用程序涉及价格,我在这里面临一个小问题。我会分步骤解释清楚 以下是我的输入和输出 输入1.01=输出1 输入1.748=输出1.75 输入1.98=输出2 输入1.49=输出1.5 输入20.0=输出2 0 我已经使用了以下代码,但我无法实现它 double calc = 1.98; DecimalFormat df = new DecimalFormat("#.##"); calc = Double.valueOf(df.for

我的应用程序涉及价格,我在这里面临一个小问题。我会分步骤解释清楚

以下是我的输入和输出

输入1.01=输出1

输入1.748=输出1.75

输入1.98=输出2

输入1.49=输出1.5

输入20.0=输出2

0

我已经使用了以下代码,但我无法实现它

    double calc = 1.98;
            DecimalFormat df = new DecimalFormat("#.##");  
            calc = Double.valueOf(df.format(calc));
            System.out.println(String.valueOf(calc).replaceAll("([0-9])\\.0+([^0-9]|$)", "$1$2"));

::> output is 1.98 which should be 2

double calc = 20.0;
        DecimalFormat df = new DecimalFormat("#.#");  
        calc = Double.valueOf(df.format(calc));
        System.out.println(String.valueOf(calc).replaceAll("([0-9])\\.0+([^0-9]|$)", "$1$2"));

 ::> output is 20 this is correct for me.

double calc = 2.01;
        DecimalFormat df = new DecimalFormat("#.##");  
        calc = Double.valueOf(df.format(calc));
        System.out.println(String.valueOf(calc).replaceAll("([0-9])\\.0+([^0-9]|$)", "$1$2"));

::> output is 2.01  Which should be 2.
下面是我尝试过的代码

输入1.01=输出1

这意味着使用零位或一位小数

输入1.748=输出1.75

这意味着添加0.05或0.005,然后使用两位小数

输入1.98=输出2

这个输出可以用上面的任一规则来描述

输入1.49=输出1.5

这意味着添加0.05或0.005,然后使用小数点后一位

输入20.0=输出20

这意味着使用零位或一位小数


因此,您的示例不是同一一致规则的所有实例。我唯一能理解的是,您只对0.25的粒度感兴趣,但这只是我的猜测。您需要优化您的需求,然后才能实现它。

试试这个。我希望它能满足你的所有要求

public static void main(String[] args) {
    double d = 20.0;
    int decimalPlaces = getDecimalPlaces(d) - 1;
    double res = Math.round(d * Math.pow(10, decimalPlaces))/Math.pow(10, decimalPlaces); // Rounding
    String text = Double.toString(Math.abs(res));
    int integerPlaces = text.indexOf('.');
    if (getDecimalPlaces(res) == 1 && text.charAt(integerPlaces + 1) == '0') 
        System.out.println((int)res);
    else
        System.out.println(res);
}

private static int getDecimalPlaces(double d) {
    String text = Double.toString(Math.abs(d));
    int integerPlaces = text.indexOf('.');
    int decimalPlaces = text.length() - integerPlaces - 1; // To Round
    return decimalPlaces;
}

你不能把它四舍五入吗?所以四舍五入到最接近的0.25?那么,当实际数字有3时,你希望精度为2位小数,当实际数字有2时,精度为1位小数?这是一个很奇怪的要求。@twntee基本上是一个毫无意义的评论。@EJP-hmm,是的,我试着给他一些我的想法,我想知道是否有人会写代码:/321.5455544546546的值没有正确输入。请检查一下,我的输出是321.545554454655。在那个例子中,你期望的输出是什么?这个代码无法处理它。为什么你不在你的帖子中提到它?我错过了它,当我是集成代码的时候,我发现了这个问题。