简体   繁体   English

如何在将双精度值转换为字符串后删除小数点

[英]How to remove decimal point from a double value after converting it to a string

I want to remove a decimal point from a double value.我想从double值中删除小数点。 I tried converting it to string我尝试将其转换为字符串

double intify(double a)
{
    String s=Double.toString(a);
    String s2=s.replaceAll(".","");
     a=Double.parseDouble(s2);
    
    return a;
    
}

If I pass 123.4567 it should return 1234567.如果我通过 123.4567,它应该返回 1234567。

replaceAll replaces a regex. replaceAll替换正则表达式。 You should use replace instead:您应该改用replace

String s2 = s.replace(".", "");

Instead of replaceAll use replace method of String:代替 replaceAll 使用 String 的replace方法:

String s2 = s.replace(".", "");

As "."作为 ”。” has a special meaning in regex and replaceAll treats source string ie first parameter as regex.在正则表达式中具有特殊含义,replaceAll 将源字符串即第一个参数视为正则表达式。

The below solves the issue of an integer being passed in ( 123 or 123.0 ), or a double in scientific notation ( 1.23E7 ):下面解决了传入整数( 123123.0 )或科学计数法中的双精度数( 1.23E7 )的问题:

Double.parseDouble(Double.toString(a).replaceAll("[.](?0$)?",""));

In your code, just change the replaceAll string to [.](?0$)?在您的代码中,只需将replaceAll字符串更改为[.](?0$)? , which states "Remove the decimal as well as the number 0 if it is right after the decimal and there's nothing after it". ,其中指出“删除小数点以及数字 0,如果它就在小数点之后并且之后没有任何内容”。

    Double i=Double.parseDouble("String with double value");


    Log.i(tag,"display double "+i);


    try{
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(0);// set as you need
        String myStringmax = nf.format(i);


        String result = myStringmax.replaceAll("[-+.^:,]","");
        Double i=Double.parseDouble(result);

       int max= Integer.parseInt(result);


    }catch(Exception e){
        System.out.println("ex="+e);
    }

您的问题对于一般答案的定义不够好,但是如果您想摆脱小数部分,只需将其解析为 double ,然后将其转换为intlong

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM