1

I want to convert 3 to 3.00. I have done explicit type conversion. but guess it doesn't seem to work!whats wrong?

my code:

#include<iostream>


using namespace std;

int main(){
    int PI = 3;
    double a = static_cast<double>(PI);
    cout<<a;


}

output: 3

Abhinav K
  • 87
  • 5
  • 1
    Why do you think this doesn't work? – BoBTFish May 26 '21 at 14:34
  • Are you aware that `3 == 3.00`? –  May 26 '21 at 14:35
  • @jabaa yes. but i would like to covert to a decimal form with two zeros after it – Abhinav K May 26 '21 at 14:37
  • 3
    you are confusing the value with its representation on your screen. For showing decimal places there are iomanipulators – 463035818_is_not_an_ai May 26 '21 at 14:38
  • That's `cout << PI << ".00";` For this simple task (integer with two zeros after it) you don't even need `iomanip`. `iomanip` is very useful for floating point numbers but overkill for integers. –  May 26 '21 at 14:39
  • @jabaa thanks, but i wanted to use the concept of type coversion. – Abhinav K May 26 '21 at 14:47
  • The problem is that type conversion doesn't help here. You don't want to change the type/value but the string representation and that's mostly unrelated to the type. Therefore `cout << PI;` (integer) and `cout << a;` (double) print the same string. –  May 26 '21 at 15:11

1 Answers1

4

This may help.

#include<iostream>

using namespace std;

int main(){
    int PI = 3;
    double a = static_cast<double>(PI);
    cout.precision(2);
    cout <<  std::fixed << a;
}
0xdw
  • 3,755
  • 2
  • 25
  • 40