English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

how do you format decimal places in C?

example: answer is 25.00000000
I want it formated to: 25.00 (two decimal places)

2007-01-21 08:15:24 · 4 answers · asked by javaHungerForce 3 in Computers & Internet Programming & Design

4 answers

Like so:

float myNum = 25.25252525;

printf("My Number: %.2f", myNum);

...that will print 2 decimal places.

printf("My Number: %.4f", myNum);

...will print 4 places.

Good luck...

2007-01-21 08:31:39 · answer #1 · answered by gene_frequency 7 · 0 0

This is real easy. You remember the printf function, right? Well that function is short for "print formatted string", which allows one to format output in a variety of ways. What you need to do is use the %f escape sequence. This code has the format %a.b[efg], where [efg] indicates that this will work with %e, %f, and %g. a represents the number of digits on the right of the decimal point, and b represents the number on the left. These are called field widths. You can figure out the rest, I hope! 8^)>

Now, following the "teach a man to fish and he'll eat for a lifetime" tack, I'll point you to the most sacred text in C programming: "The C Programming Language" by Brian Kernighan and Dennis Ritchie. Not only does it provide the C programmer with an exhaustive language reference, complete with syntax and grammar definitions, but it also serves as a newbie tutorial to C.

Good luck!

2007-01-21 08:24:58 · answer #2 · answered by twelfthdimensiontraveller 1 · 0 0

because it really is an int, the variety after the decimal aspect will always be 0. so that you may want to easily troublesome code it: cout << type << ".0"; in case you anticipate to ever see .a million or .6 or .9 or .in spite of except 0, then yeah, you pick to be using a double the following, no longer an int.

2016-10-17 02:39:44 · answer #3 · answered by ? 4 · 0 0

%.2f if you are using printf()

2007-01-21 15:39:00 · answer #4 · answered by dand370 3 · 0 0

fedest.com, questions and answers