c++:如何使用美元符号将双精度格式化为货币
c++: How do I format a double to currency with dollar sign?
我有一个函数,它接受一个双精度并将其作为带有千位分隔符的字符串返回。你可以在这里看到它: c ++:用逗号格式化数字?
#include <iomanip>
#include <locale>
template<class T>
std::string FormatWithCommas(T value)
{
std::stringstream ss;
ss.imbue(std::locale(""));
ss << std::fixed << value;
return ss.str();
}
现在我希望能够将其格式化为带有美元符号的货币。 具体来说,如果给定 20,500 的双倍,我想得到一个字符串,例如"$20500"。
在负数的情况下,前面加上美元符号不起作用,因为我需要"-$5,000"而不是"$-5,000"。
if(value < 0){
ss << "-$" << std::fixed << -value;
} else {
ss << "$" << std::fixed << value;
}
我认为你唯一能做的是
ss << (value < 0 ? "-" : "") << "$" << std::fixed << std::abs(value);
您需要特定的区域设置才能使用千位分隔符进行打印。
这是我用来学习格式化从这里提取的货币的示例程序。尝试将该程序分开,看看您可以使用什么。
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void showCurrency(double dv, int width = 14)
{
const string radix = ".";
const string thousands = ",";
const string unit = "$";
unsigned long v = (unsigned long) ((dv * 100.0) + .5);
string fmt,digit;
int i = -2;
do {
if(i == 0) {
fmt = radix + fmt;
}
if((i > 0) && (!(i % 3))) {
fmt = thousands + fmt;
}
digit = (v % 10) + '0';
fmt = digit + fmt;
v /= 10;
i++;
}
while((v) || (i < 1));
cout << unit << setw(width) << fmt.c_str() << endl;
}
int main()
{
double x = 12345678.90;
while(x > .001) {
showCurrency(x);
x /= 10.0;
}
return 0;
}
相关文章:
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 正在将csv文件读取为双精度矢量
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 如何在C++中的同一函数中使用字符串和双精度
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 检查是否以特定精度给出双精度
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- C 字符串返回字符串的整数/双精度/长整型值
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 如何使双精度值的 C++ 和 C# 中的结果相同
- 使用浮点数和双精度数的非常小数字的数学
- 使用 Xcode 将双精度存储在数组C++中
- 在 C++ 中将双精度变量写入二进制文件
- 如何从字符串转换为双精度*
- 为什么我的数组双精度函数不起作用?
- 高精度双精度的 Sprintf 格式化问题
- 使用 sprintf 格式化负整数/双精度
- 在c++中格式化双精度值
- 格式化的双精度输出
- 以二进制格式格式化 2D 双精度矩阵以读取 IDL 的最基本方法是什么?