Janssen Marasigan
Janssen Marasigan

Reputation: 19

Variable for 1865345.934 in c++?

How can I cout 1865345.934?

what variable should I use?

#include<iostream>
using namespace std;
int main(){
    price=1865345.934;
    cout << price;
    return 0;
}

If i use int the decimal does not appear on the output while if i use double it shows 1.86535e+006.

Upvotes: 0

Views: 136

Answers (3)

Costantino Grana
Costantino Grana

Reputation: 3428

This was already suggested in Pepijn Kramer answer, but for the lazy one:

#include <print>

int main()
{
    double price = 1865345.934;
    std::println("{:3}", price);
    return 0;
}

C++ is finally getting its print/println functions!

Upvotes: 1

Pepijn Kramer
Pepijn Kramer

Reputation: 13076

A more C++20 idiomatic way is to use std::format (or std::print in C++23). See below:

#include <iostream>
#include <format>

//using namespace std; <== stop doing this

int main()
{
    double price=1865345.934;
    std::cout << std::format("{:3}", price);
    return 0;
}

Upvotes: 7

dheeraj singh
dheeraj singh

Reputation: 46

You can use std::setprecision() and specify how many decimal places it should print.

Example:

#include <iomanip>
#include <iostream>

int main() {
    double price = 1865345.934;
    std::cout << std::fixed << std::setprecision(3) << price << '\n';
}

Upvotes: 3

Related Questions