[英]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(".", "");
The below solves the issue of an integer being passed in ( 123
or 123.0
), or a double in scientific notation ( 1.23E7
):下面解决了传入整数(
123
或123.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 ,然后将其转换为int
或long
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.