c ++将打印格式从整数2255更改为$ xx.xx

时间:2018-10-16 01:42:28

标签: c++

我有函数return int i = 2255,这意味着我口袋里有多少美分,我想以$ xx.xx格式打印 我如何将其打印到22.55?非常感谢

2 个答案:

答案 0 :(得分:0)

printf("$%d.%d", i / 100, i % 100);

printf("$%0.2f", double(i) / 100);

尽管如此,在C ++ 11和更高版本中,请考虑将std::coutstd::put_money()结合使用:

#include <iostream>
#include <iomanip>

std::cout << std::put_money(double(i) / 100);

答案 1 :(得分:-1)

一种方法是设置cout流以打印所需的格式:

#include <iostream>
#include <iomanip>

int main()
{
    int i = 2250;

    std::cout << std::fixed;
    std::cout << std::setprecision(2);
    std::cout << i/100.0 << std::endl;  // Divide by 100.00 to convert to double

    return 0;
}