概述
1
double num = 1234567.1234567;
std::cout << num << "n";
std::cout.setf(std::ios::fixed, std::ios::floatfield);
std::cout << num << "n";
std::cout.precision(4);
std::cout << num << "n";
2 string 格式化
#include <stdlib.h>
#include <string>
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <limits>
#include <sstream>
using namespace std;
string do_fraction(long double val, int decplaces=3)
{
ostringstream out;
char DECIMAL_POINT='.'; // 欧洲用法为','
int prec=numeric_limits<long double>::digits10; // 18
out.precision(prec);//覆盖默认精度
out<<val;
string str= out.str(); //从流中取出字符串
size_t n=str.find(DECIMAL_POINT);
if ((n!=string::npos) //有小数点吗?
&& (str.size()> n+decplaces)) //后面至少还有decplaces位吗?
{
str[n+decplaces]='