Hi, is there a quick way to format a float variable that is 0.775 to display it as 77.5? Thanks
To better clarify, im doing a simple little tasks of
variable = variable / variable to find the percentage of something.
Hi, is there a quick way to format a float variable that is 0.775 to display it as 77.5? Thanks
To better clarify, im doing a simple little tasks of
variable = variable / variable to find the percentage of something.
A quick, practical complement to and the replies from and .
Scaling a fraction to percent and controlling output formatting are the right ideas. A few points that help keep results stable and readable over time: prefer double for the math to reduce representation error; make sure at least one operand is floating when dividing to avoid integer division; check for divide-by-zero; and be aware that binary floating-point can make values like 0.775 look slightly off when printed (formatting or explicit rounding is the right remedy — see Floating-point arithmetic).
Practical options for display:
std::fixed + std::setprecision) — see std::setprecision.std::format can produce the same result with a format string — see std::format.std::round before output — see std::round.Example snippets (illustrative; adjust names/types to match existing code):
// format with iostreams
std::cout << std::fixed << std::setprecision(1) << percent_value << '%' << '\n'; // C++20 std::format
std::cout << std::format("{:.1f}%", percent_value); Check types and handle zero denominators before computing the percent. These steps make the display consistent and avoid surprises from floating-point representation.
Jump to Post— Dave Sinkula 2,398Multiply by 100. (Isn't that an elementary school question?)
Multiply by 100. (Isn't that an elementary school question?)
hah, I didn't even think of that lol. Thanks for the obvious answer =D
I think there is a way to do it by manipulating the output stream's formatting, but I'm not totally familiar with that yet.
In the meantime, you could just multiply by 100 when you output it.
float percent = 0.0f;
float value1 = 12.0f;
float value2 = 48.0f;
percent = value1 / value2;
std::cout << "Your percentage is: " << (percent * 100) << std::endl; EDIT:
Looks like Dave beat me to it...
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.