Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ equivalent of printf() or formatted output

Tags:

c++

printf

cout

I am relatively new to the C++ world. I know std::cout is used for console output in C++. But consider the following code in C :

#include<stdio.h>

int main(){
    double dNum=99.6678;
    printf("%.02lf",dNum);
    //output: 99.67
 return 0;
}

How do I achieve the similar formatting of a double type value upto 2 decimal places using cout in C++ ?

I know C++ is backward compatible with C. But is there a printf() equivalent in C++ if so, then where is it defined ?

like image 527
Abrar Avatar asked Nov 30 '22 17:11

Abrar


1 Answers

This is what you want:

std::cout << std::fixed << std::setprecision(2);
std::cout << dNum;

and don't forget to :

#include <iostream>
#include <iomanip>
like image 150
vishal Avatar answered Dec 05 '22 16:12

vishal