What is this format specifier?

What is %.2f? Why is it not just %f? Is there some additional calculation happening? The half function already does all the calculations including splitting the bill, so I’m not sure what %.2f is. (Btw why is this code not formatting correctly in lemmy?)


<span style="color:#323232;">
</span><span style="color:#323232;">#include 
</span><span style="color:#323232;">#include 
</span><span style="color:#323232;">
</span><span style="color:#323232;">float half(float bill, float tax, int tip);
</span><span style="color:#323232;">
</span><span style="color:#323232;">int main(void)
</span><span style="color:#323232;">{
</span><span style="color:#323232;">    float bill_amount = get_float("Bill before tax and tip: ");
</span><span style="color:#323232;">    float tax_percent = get_float("Sale Tax Percent: ");
</span><span style="color:#323232;">    int tip_percent = get_int("Tip percent: ");
</span><span style="color:#323232;">
</span><span style="color:#323232;">    printf("You will owe $%.2f each!n", half(bill_amount, tax_percent, tip_percent));
</span><span style="color:#323232;">}
</span><span style="color:#323232;">
</span><span style="color:#323232;">// TODO: Complete the function
</span><span style="color:#323232;">float half(float bill, float tax, int tip)
</span><span style="color:#323232;">{
</span><span style="color:#323232;">    bill += (bill * (tax / 100.0));
</span><span style="color:#323232;">    bill += (bill * (tip / 100.0));
</span><span style="color:#323232;">
</span><span style="color:#323232;">    bill /= 2;
</span><span style="color:#323232;">
</span><span style="color:#323232;">    return bill;
</span><span style="color:#323232;">}
</span>
DirigibleProtein,

man printf

GuybrushThreepwo0d,

This is the way

Maoo,
@Maoo@hexbear.net avatar

%.2f% means it will format to two decimal places max. So 5.877 will format as 5.88 and 1 will format as 1.00.

steersman2484,

Please put your code between tripple backticks in a seperate line above an below your code. Single backticks are only for inline code like this.

To answer your question, the %.2f means it should only print two digits after the decimal point.

You can also use some other variations like this:

  • %2f print the number at least 2 characters wide
  • %5.2 print the number at least 5 characters wide with a precision of two digits after the decimal point
  • %05.2 the same as above, but fill leading digits with zeros

This is just formatting, play a bit around with it and you will get it.

Bougie_Birdie, (edited )

%.2f will format your number rounded to two decimal places. So if you had 1 / 3 it would come out as 0.33 instead of 0.333333

% is the placeholder for the value

.2 tells it ‘two spaces after the decimal’

f tells it that the placeholder is a float

ono,

It’s a decimal floating point specifier with a precision sub-specifier.

cplusplus.com/reference/cstdio/printf/

joyjoy,

Example with pi.


<span style="font-weight:bold;color:#a71d5d;">#define </span><span style="color:#323232;">PI </span><span style="color:#0086b3;">3.1415926
</span><span style="color:#323232;">
</span><span style="font-weight:bold;color:#a71d5d;">int </span><span style="font-weight:bold;color:#795da3;">main</span><span style="color:#323232;">() {
</span><span style="color:#323232;">  </span><span style="color:#62a35c;">printf</span><span style="color:#323232;">(</span><span style="color:#183691;">"</span><span style="color:#0086b3;">%.2f</span><span style="color:#183691;">"</span><span style="color:#323232;">, PI); </span><span style="font-style:italic;color:#969896;">// prints 3.14
</span><span style="color:#323232;">  </span><span style="font-weight:bold;color:#a71d5d;">return </span><span style="color:#0086b3;">0</span><span style="color:#323232;">;
</span><span style="color:#323232;">}
</span>
Touching_Grass,

This answer makes me so angry like revisiting trauma from learning programming. I just remember asking questions early on and getting answers more confusing that are even harder to parse

ono, (edited )

This answer makes me so angry like revisiting trauma from learning programming.

If you bothered to read the documentation, which exists in abundance on the web, in many books, in the built-in manuals of various operating systems and dev tools, and which I also linked in my answer, you would see a full explanation with clear examples.

But you can’t be bothered with any of that, and instead expect other people to spend their time writing custom tutorials just for you?

Your anger is misplaced. Please consider taking a walk.

I just remember asking questions early on and getting answers more confusing that are even harder to parse

When you ask people questions about their field of knowledge, and they don’t know you, it’s reasonable for their answers to assume you know the rudimentary basics. (Just as it would be reasonable for a fourth-year group to assume a that a stranger asking them questions has at least taken the first-year class.) Asking beyond your level of experience is not necessarily bad, but you should be ready to describe what you don’t understand about the answer, so that people can either elaborate with a helpful level of detail or send you to a forum more appropriate for your needs. For example:

!learn_programming

Touching_Grass,

I’m even angrier now.

BitsOfBeard,
@BitsOfBeard@programming.dev avatar

Go touch some gr… Oh, you are touching grass already??

Touching_Grass,

Just touching some Poaceae

abhibeckert,

instead expect other people to spend their time writing custom tutorials just for you?

Nobody asked you to spend your time helping people out on Lemmy, if you don’t want to do it, then don’t do it. There’s plenty of people here who are happy to do that.

And I don’t think it is reasonable to expect people to understand the basics. If they did, then they wouldn’t have asked.

ono,

And I don’t think it is reasonable to expect people to understand the basics.

If we assumed everyone asking a question knows nothing at all of the surrounding topic, and responded at length addressing every related detail instead of what was asked, our answers would be tedious, and often annoying. It’s called overexplaining (among other things). It’s usually better to tailor the answer to the cues given by the person asking, and let them ask more questions if necessary.

If they did, then they wouldn’t have asked.

OP didn’t ask about the basics. They clearly know them already, as we can see from the language and specificity of their question. I was happy to answer and provide a link for deeper detail.

But then someone else came along who apparently knew less than OP did, and decided express anger at me for not preemptively guessing and catering to their unstated special needs, in an answer that wasn’t intended for them in the first place. That was incredibly entitled and rude.

JackbyDev, (edited )

Which part of that is confusing to you? We can help make it easier to understand.

Edit: Oh, this isn’t even OP.

Touching_Grass,

Its not confusion to me, I get what it is. Its the style of answer. Its like if you see a dog, ask what it is and someone answers Canis lupus familiaris.

There’s no grokking that. You either know or you don’t. If they’re asking what .2f then lots of answers here do a good job describing that it formats the value to two decimal places. We can all do something with that at any level.

Saying its a crombopulater sub cablator is much harder to process. It just seems like an answer thats likely to make the person to have to ask more questions or frustrated

Turun,

Its like if you see a dog, ask what it is and someone answers Canis lupus familiaris.

…and gives you a link to the Wikipedia page about dogs.

It’s not a good answer in the sense that they did not do the work of copying and rephrasing the content of the website they linked, you have to do some of the work yourself. But it’s a very thorough answer that gives you all the information you need about formatting. Including examples of pretty much exactly the question OP asked.

JackbyDev,

I’m not looking for meta level criticism of this style of advice, I’m trying to ask OP what was confusing on this page and help them learn how to read this page specifically. I’m not saying OP should be able to understand this page. I’m not saying this style of advice is acceptable or not.

Edit: Nevermind, I thought OP posted that comment.

abhibeckert,

The confusion is you just provided sample code showing how “%.2f” works - you didn’t answer the question which was what does that sequence of characters actually mean? What does the % do. What does the . do. What does the 2 do. What does the f do.

OP needs to know the answer to all of those.

JackbyDev, (edited )

OP got the answer to those in another comment, I’m asking what part they need help understanding in this link. Also, I didn’t provide the link.

Edit: Nevermind, I mistook the comment for being OP.

AlmightySnoo,

If you want multi-line code, you need to put it like this:

https://lemmy.world/pictrs/image/c74eaa9e-411a-458c-b1a8-ea9557099037.png

For these kinds of questions, your best friend is the documentation. In particular, a man ‘printf(3)’ yields:

Format of the format string

The format string is a character string, beginning and ending in its initial shift state, if any. The format string is composed of zero or more directives: ordinary characters (not %), which are copied unchanged to the output stream; and conversion specifications, each of which results in fetching zero or more subsequent arguments. Each conversion specification is introduced by the character %, and ends with a conversion specifier. In between there may be (in this order) zero or more flags, an optional minimum field width, an optional precision and an optional length modifier.

The overall syntax of a conversion specification is:

%[$][flags][width][.precision][length modifier]conversion

starman,
@starman@programming.dev avatar

Wait, you can use man on C functions?

Eufalconimorph,

On libc functions yes. Maybe on some from other libs, if they provide man pages.

starman,
@starman@programming.dev avatar

That’s nice.

AlmightySnoo,

Yup! Try also man malloc 😁

starman,
@starman@programming.dev avatar

Nice :)

ono, (edited )

You can if you have those man pages installed.

You might also enjoy man ascii, man operator, or even man intro.

Unfortunately, there are still some gaps:


<span style="color:#323232;">$ man love
</span><span style="color:#323232;">No manual entry for love
</span>
JBloodthorn,
@JBloodthorn@kbin.social avatar

Back in my day, MS-DOS let you use HELP on QBASIC commands.

PoolloverNathan,

Wouldn’t man 3 printf do the same thing without the quotes?

AlmightySnoo,

Yup that definitely does the same thing.

If anyone else is wondering why the 3 is there, it’s because usually you won’t find just one printf. You have the printf user command, the printf function from the standard C library, and POSIX manual entries for both the printf user command and C function. The id number is then an identifier for the corresponding section of the printf entry, and you can list all of them by doing a man -f printf.

ono,

The id number is then an identifier for the corresponding section of the printf entry,

Nit: 3 is the manual section in which to look for the named entry (aka page), not a section of the entry.

AlmightySnoo,

Wrote it in an awkward way but yeah I meant to say the section where you can find the corresponding entry 😬

JackbyDev,

Awesome, I think I’m gonna consider aliasing man to man -f lol. Can you think of any compelling reason not to?

Actually, nevermind, I misunderstood you. -f just lists the pages, it doesn’t print all of their content.

qaz,

This formats the number with 2 decimals behind the dot.

sharedburdens,

The .2f just means the float displays with only 2 significant figures ie cents.

  • All
  • Subscribed
  • Moderated
  • Favorites
  • random
  • uselessserver093
  • Food
  • aaaaaaacccccccce
  • [email protected]
  • test
  • CafeMeta
  • testmag
  • MUD
  • RhythmGameZone
  • RSS
  • dabs
  • Socialism
  • KbinCafe
  • TheResearchGuardian
  • oklahoma
  • feritale
  • SuperSentai
  • KamenRider
  • All magazines