Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float / Float = strange result

I have two values, one from user input and another from DB.

var userinput = form["someInput"];
var valuefromDB = GetValue(someNumber);

public float? GetValue(int id){
return (float?) db.table.where(p=> p.id == id).select(p=> p.Value).SingleOrDefault();
}

userinput have value "1" as string, while valuefromDB havevalue 0.001 as float.

so 1 / 0.001 = 1000

but my c# code give me 999.999939 as result;

var final = float.Parse(userinput) / valuefromDB

when i have "2" as user input value, result is correct, 2000...

like image 322
Novkovski Stevo Bato Avatar asked Mar 28 '26 03:03

Novkovski Stevo Bato


1 Answers

That's because not all decimal numbers can be accurately represented in binary (which is the representation that float uses). The solution is to format the result to the desired number of decimal places, which will cause it to be rounded and displayed "correctly" as a consequence.

Update: To format a float for display, take a look at this MSDN reference page and this page of examples.

like image 139
Jon Avatar answered Mar 29 '26 17:03

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!