c - How to ensure that floating-point variables entered with 2 decimal places retain their exact value -


is there way ensure floating-point variable entered user, having 2 decimal places after decimal point, retains exact value, rather losing precision?

this example case: want round float 50 numbers after radix point, this

before rounding = 0.70999997854232788085937500000000000000000000000000

to this:

after rounding = 0.71000000000000000000000000000000000000000000000000

i became confused when wanted compare float number in condition this:

== program start==
input : 0.71

/* program logic */ if (input == 0.71) {     printf("true !");      } else {     printf("false !"); } 

output : false !
==program end==

the output false ! , false ! because true value of user's input 0.70999997854232788085937500000000000000000000000000, , not 0.71000000000000000000000000000000000000000000000000

is there way round float value that? read potential inaccuracies floating point here:

however, these don't answer question. if use ceilf(input * 100) / 100 function, make input 0.71 0.71000 when printf()d using %.5f format - seems work. when print %.50f, real input value appears 0.709999978542327880859375. so, can't compare value in condition.

so, if floating point can never accurate, trick program logic above true return value @ condition?

all of user's input comes in text. easiest -- and, possibly, safest -- way check compare string before converting number:

if (strcmp("0.71", input) == 0) {     printf("true !"); } else {     printf("false !"); } 

of course, may not acceptable you, if wish check other equality :)

the other point interested in fixed, rather floating numbers here -- confusing them actual integers. if hundredths you'd work with, work integer numbers of hundredths... example, consider money -- instead of using float (or double) store amounts of dollars (like $7.61), use int (or, god bless you, long) store cents (like ¢761).

similarly, example, if counting time , need precision of 1 thousandth of second, use integer numbers of milliseconds, instead of floating-point number of seconds.

this sidestep entire problem altogether , may make programs faster...


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -