如果原来的小数位数少于
如果原来的小数位数多于
#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);
}
} package main
import (
"fmt"
"strconv"
)
func main() {
str := ""
fmt.Scan(&str)
intPart := 0
poitPart := 0
i := 0
for ; i < len(str); i++ {
if str[i] == '.' {
break
}
t, _ := strconv.Atoi(string(str[i]))
intPart = 10*intPart + t
}
for j := i + 1; j < len(str); j++ {
t, _ := strconv.Atoi(string(str[j]))
poitPart = 10*poitPart + t
if j > i+3 {
break
}
}
for poitPart > 0 && poitPart < 1000 {
poitPart = poitPart * 10
}
poitPart = (poitPart + 5) / 10
fmt.Printf("%d.%.03d\n", intPart, poitPart)
}
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();
}
}