在C#中将double转换为float [英] Convert double to float in C#

查看:1682
本文介绍了在C#中将double转换为float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have to convert result double to float 
i got answer in following format:2,92571853323781
and want answer as 2.9257





我尝试过:



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;

返回结果;



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;

推荐答案

尝试 ToString()

Try ToString():
double d = 2.92571853323781;
string result = d.ToString("0.0000"); // gives 2.9257


绝对没有理由将double转换为float,因为double是更宽的类型。也就是说,即使需要浮动作为输入,在所有这些情况下,也可以使用double;转换将隐式完成。当然,情况恰恰相反;转换是通过regular()运算符完成的: float a =(float)b; //其中b是double;它可能会失败



您所需要的可能根本与转换无关,而仅仅与某些数字的字符串表示有关。通过适当的格式化可以解决此问题。所有您需要知道的是:

Double.ToString方法(系统) [ ^ ],

标准数字格式字符串 [ ^ ],

自定义数字格式字符串 [ ^ ]。



这就是全部。



-SA
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


这篇关于在C#中将double转换为float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆