如何对小数位进行分组
How to group decimal places as well?
本文关键字:小数 更新时间:2023-10-16
我想得到x = 1,234,567,890.098,765,432,1
.
#include <iostream>
#include <string>
#include <iomanip>
#include <locale>
using namespace std;
struct separated : numpunct<char>
{
string do_grouping() const { return " 3"; }
};
int main()
{
const double x = 1234567890.0987654321;
locale our_local(cout.getloc(), new separated);
cout.imbue(our_local);
cout << fixed;
cout << setprecision(10);
cout << "x = " << x << endl;
return 0;
}
输出:x = 1,234,567,890.0987654321
预期输出:x = 1,234,567,890.098,765,432,1
如果你能使它更通用,那就更好了,如下所示,
-
x = 1'234'567'890.098'765'432'1
-
x = 1_234_567_890.098_765_432_1
小数点为点 (US-EN(。
问题
如何对小数位进行分组?
编辑
x
属于 double
类型,而不是文本字符串。
这是一个算法:
创建一个函数,该函数将要转换的数字作为其参数。 将该数字转换为字符串。 扫描字符串中的小数点(同时注意非数字结果(如无穷大或不确定(的可能性(。 如果找到,请处理字符串的其余部分,每隔三个数字插入分隔符,到达字符串末尾或非数字(例如,指定指数的E
(时停止。 返回此字符串。
附加练习,创建此函数的一个版本,该版本可以作为操纵器传递给cout
。
相关文章:
- C++将浮点指针值舍入为小数位数
- 从给定的 I 和 D 序列中形成最小数
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用 std::index_sequence 初始化具有固定大小数组成员的 POD 结构容器
- 计算 PI 最多 42 位小数
- 为什么我必须添加一个小数才能在C++中正确计算此数学
- 返回浮点数的小数位数
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 在数学上将浮点数四舍五入到 N 位小数
- 打印双精度的整个非小数部分
- 声明后,gcc 的动态大小数组是否与标准数组有效相同?
- 如何在C++中对OpenCV垫的小数进行四舍五入?
- 将 int 数组转换为带有小数C++的双精度数组
- Arduino如何制作返回固定大小数组的函数
- 从浮点数中删除小数部分但保留类型的有效方法
- 分配新的零大小数组可以具有有效价值吗?
- c++只关心2位小数,没有设置精度
- 有没有一种方法可以在不设置精度的情况下设置小数位数
- gcc c++编译器中的零大小数组
- 给出了一个数的确切除数(n),如何确定具有n个除数的最小数?