How to identify whether a fractional part of a number contains more that 2 digits.

224 Views Asked by At

EX. I want to accept numbers which have maximum of 2 digits after decimal points. i, e, 10.23 should be allowed and 10.233 should not be allowed. What mathematical operations can be done to distinguish these two numbers. These numbers are coming as an input from the console. Please help, Thanks

2

There are 2 best solutions below

0
On

For a number $x$ look at the fractional part of $100x$. If it is non-zero, then you have more than 2 decimal points

Example:

$\{100(10.23)\}= \{1023.0\} = 0$

$\{100(10.233)\}= \{1023.3\} = 0.3$

1
On

Presumably you have the floor (greatest integer) function available. $100x=\lfloor 100x\rfloor$ if and only if $x$ has at most two digits after the decimal point.