PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 7, 2022

[FIXED] How to check if float is a whole number?

 August 07, 2022     c++, decimal, floating-point, rounding     No comments   

Issue

The printf function's %g is able to show the whole number 3 if the float is 3.00, and will show 3.01 if the float's value isn't a round number float.

How would you do this yourself through some code, without formatting the number as a string?


Solution

There isn't really a simple answer

Integral values do have exact representations in the float and double formats. So, if it's really already integral, you can use:

f == floor(f)

However, if your value is the result of a calculation which at one point involved any sort of non-zero fractional part, then you will need to be concerned that you may have something very close to an integer but which isn't really, exactly, to-the-last-bit the same. You probably want to consider that to be integral.

One way this might be done:

fabs(f - round(f)) < 0.000001

And while we are on the subject, for the purists, we should note that int i = f; or double i = f; will round according to the FPU mode whereas round(3) will round half-way cases away from zero.



Answered By - DigitalRoss
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing