Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
C#
I have to convert result double to float 
i got answer in following format:2,92571853323781
and want answer as 2.9257


What I have tried:

double rlat1 = Math.PI * Convert.ToDouble(19.118479) / 180;
double rlat2 = Math.PI * (19.111864) / 180;
double theta = Convert.ToDouble(72.852074) - (72.879028);
double rtheta = Math.PI * theta / 180;
double dist =Math.Sin(rlat1) * Math.Sin(rlat2) + Math.Cos(rlat1) * Math.Cos(rlat2) * Math.Cos(rtheta);
dist = Math.Acos(dist);
dist = dist * 180 / Math.PI;
dist = dist * 60 * 1.1515;
double result= dist*1.609344;
return result;
Posted
Updated 23-May-16 20:36pm
Comments
Kornfeld Eliyahu Peter 24-May-16 2:32am    
And hot that connected to double-to-float conversation...The problem is that the number you got has a different decimal separator (comma) from the one you want (dot)...And that depends on your locals!!!

Try ToString():
C#
double d = 2.92571853323781;
string result = d.ToString("0.0000"); // gives 2.9257
 
Share this answer
 
Comments
Member 11466758 24-May-16 2:43am    
BY USING ABOVE I GOT SAME OUTPUT AS 2,9257
Mehdi Gholam 24-May-16 2:45am    
Check your regional settings for decimal separator character i.e. "." instead of ","
Member 11466758 24-May-16 2:57am    
I got output as 2.9257. thanks!
There is absolutely no reason to convert double to float, because double is "wider" type. That is, even if float is required as input, in all such cases, double can be used; the conversion will be done implicitly. The opposite is not true, of course; and the conversion is done via a regular () operator: float a = (float)b; // where b is double; it may fail.

What you need is probably not related to "conversion" at all, but merely to the string representation of some numbers. This problem is solved via proper formatting. All you need to know is this:
Double.ToString Method (System)[^],
Standard Numeric Format Strings[^],
Custom Numeric Format Strings[^].

That's all.

—SA
 
Share this answer
 
Comments
Member 14818643 6-May-20 11:26am    
I'm running into an error where my script is telling me that I cannot convert a double to a float, even though i was trying to work with a float in the first place.

Unfortunately, every single answer I can find on the internet assumes that people are trying to output a string.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900