Double转String 去掉小数点
时间: 2023-08-16 09:14:10 浏览: 127
要将`Double`类型的值转换为不带小数点的字符串,你可以使用`DecimalFormat`类。以下是一个示例代码:
```java
import java.text.DecimalFormat;
public class DoubleToStringExample {
public static void main(String[] args) {
Double number = 3.14159;
// 创建DecimalFormat对象,指定格式为不带小数点
DecimalFormat decimalFormat = new DecimalFormat("0");
// 格式化Double值为字符串
String str = decimalFormat.format(number);
System.out.println(str); // 输出: "3"
}
}
```
在上面的示例中,我们创建了一个`DecimalFormat`对象,并指定了格式为不带小数点的样式模式 `"0"`。然后,我们使用`format()`方法将`Double`类型的值格式化为字符串。最终结果中不包含小数点。
你可以根据需要自定义格式化的样式模式,例如 `"0.00"`表示保留两位小数的数字。
相关问题
string去除小数点后多余的0
可以使用sprintf函数将浮点数转换为字符串,然后使用正则表达式去除小数点后多余的0。具体代码如下:
```c
#include <stdio.h>
#include <regex.h>
int main() {
double num = 3.140000;
char str[20];
sprintf(str, "%.6f", num); // 将浮点数转换为字符串,保留6位小数
regex_t reg;
regcomp(®, "\\.?0+$", REG_EXTENDED); // 编译正则表达式
regmatch_t pmatch[1];
if (regexec(®, str, 1, pmatch, 0) == 0) { // 匹配成功
str[pmatch[0].rm_so] = '\0'; // 将多余的0去掉
}
regfree(®); // 释放正则表达式
printf("%s\n", str); // 输出结果:3.14
return 0;
}
```
Double 类型四舍五入去除小数点
如果你想要将 Double 类型的数四舍五入并去除小数点,可以使用 DecimalFormat 类进行格式化输出。以下是一个示例代码:
```java
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
Double d = 123.456;
DecimalFormat df = new DecimalFormat("#");
String s = df.format(d);
System.out.println(s); // 输出 123
}
}
```
在以上代码中,使用了 DecimalFormat 类对 Double 类型进行了格式化输出。其中,# 表示数字,. 表示小数点,使用 #. 表示保留小数点后面的数字。由于这里只需要去掉小数点,不需要保留小数点后面的数字,所以使用了 # 表示不保留小数点后面的数字。最后将格式化后的结果转换为字符串输出即可。