不要四舍五入,
如果没有小数位,将小数点后面的.0改成.00(比如2转换成2.00,而不是2.0)
不知道会有多少位小数,有多少位显示多少位
比如这种的
88.495000
将后面的0给去掉
要是88.495236
就不用去掉
如果是六个0就保留小数点后两位
比如
100.000000
改成
100.00
public static void main(String[] args) {
double d = 1203.456000;
int d2= (int) d;
String s1 = String.valueOf(d);
if (s1.contains(".")&d2!=d){
int i = s1.indexOf(".");
for(int j=i;j<s1.length()-1;j++){
int lastIndex=s1.charAt(s1.length()-1);
int io = s1.lastIndexOf("0");
if (lastIndex==io){
s1=s1.substring(0,s1.length()-1);
}
}
}else {
s1+="0";
}
System.out.println(s1);
}
你可以检验一下
新人前端 也来凑凑热闹,大佬勿喷哟 但是欢迎指正
function conversion(a) {
if (Math.ceil(a) === a) {
console.log("我是整数");
console.log(a.toFixed(2));
} else {
console.log("我不是整数");
console.log(String(a));
}
}
conversion(8.0000100000)
%.2f
可以使用正则表达式实现
#include <iostream>
#include <algorithm>
using namespace std;
string truncate_tail_zeros(const string &str)
{
if (str.find_first_of('.') == string::npos)
return str + ".00";
string r;
auto itr = find_if(str.rbegin(), str.rend(), [](auto c)
{ return c != '0'; });
reverse_copy(itr, str.rend(), back_inserter(r));
if (*itr == '.')
r += "00";
return r;
}
int main()
{
string str;
while (cin >> str)
cout << "=> " << truncate_tail_zeros(str) << endl;
return 0;
}
$ g++ -Wall main.cpp
$ ./a.out
100
=> 100.00
100.0
=> 100.00
100.000
=> 100.00
100.0012345600
=> 100.00123456
public void StrFm(String str){
int tailNum = new BigDecimal(str).stripTrailingZeros().scale();
if (tailNum <= 0){
return str +".00";
} else {
return str;
}
}
@Test
public void test1A(){
DecimalFormat decimalFormat = new DecimalFormat("#.00");
String format = decimalFormat.format(2);
log.info("format:{}",format);
}
直接操作字符串,不需要转换为数值型。实现效果如下,功能函数在work中,满意的话请采纳
public static String wrok(String string){
int i = string.indexOf(".");//寻找小数点
if(i==-1){
//没找到,在后面加上.00直接返回
return string+=".00";
}else{
//找到了
if(string.substring(string.indexOf(".")+1,string.length()).equals("000000")){
//如果小数后面后面六个是0,那么就替换成00
string=string.replace("000000","00");
}else{
//如果最后一位小数是0,去掉零
while (string.lastIndexOf("0")==string.length()-1){
string=string.substring(0,string.lastIndexOf("0"));
}
}
}
//返回结果
return string;
}
请采纳