如果原来的小数位数少于
如果原来的小数位数多于
#include<iostream>
#include<iomanip>
using namespace std;
int main(){
double a;
cin >> a;
cout << fixed << setprecision(3) << a << endl;
return 0;
} using System;
public class Program {
public static void Main() {
//获取输入
string line = System.Console.ReadLine ();
//查找小数点位置
int index = line.IndexOf('.');
if (index == -1 ) { //没找到,是整数,要补三个0
line += ".000";
} else if (line.Length - 1 - index < 3) { //小数位数少于 3 ,需要补充 0
int n = 3 - (line.Length - 1 - index); //补的数量
for (int i = 0; i < n; i++)
line += "0";
} else if (line.Length - 1 - index >
3) { //小数位数大于 3 ,需要四舍五入
double number = double.Parse(line);
number = Math.Round(number, 3);
line = number.ToString();
}
System.Console.WriteLine(line);
}
} double d = in.nextDouble();
System.out.println(String.format("%.3f",d)); import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
float n = in.nextFloat();
// 使用DecimalFormat 格式化小数,保留3位小数
DecimalFormat df = new DecimalFormat("0.000");
String s = df.format(n);
System.out.println(s);
in.close();
}
}