如何将浮点数减少到小数点后第2位 [英] how to decrement the float up to 2 place after decimal

查看:103
本文介绍了如何将浮点数减少到小数点后第2位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用asp.net 4.0

我如何将float变量减至小数点后2位?


34.6789878至34.678

i am using asp.net 4.0

how can i decrement the float variable up to 2 place after decimal

i.e.
34.6789878 to 34.678

推荐答案

使用 Math.Round [^ ]


"float m1 = Convert.ToInt32(TextBox11.Text);
float m2 = Convert.ToInt32(TextBox12.Text);
浮点m3 =(m1/m2)* 100;

那么我在哪里使用math.round .... ??"


为什么要使用ToInt32转换为浮点数?

改用它:
Use Math.Round[^]


"float m1 = Convert.ToInt32(TextBox11.Text);
float m2 = Convert.ToInt32(TextBox12.Text);
float m3 = (m1 / m2) * 100;

then where i use math.round....??"


Why are you converting to floats, using ToInt32?

Use this instead:
float m1 = Convert.ToSingle(TextBox11.Text);
float m2 = Convert.ToSingle(TextBox12.Text);
float m3 = (float) Math.Round((m1 / m2) * 100, 3);

或更好地使用TryParse对其进行转换,因为如果用户输入以下错误,则可以报告该用户错误"Hello"而不是"123.45".
此外,您还应该检查输入内容:如果用户在TextBox12中输入"0",则代码将引发Divide by Zero异常.

顺便说一句:
1)在答复时删除您的问题是很不礼貌的,并且可能使人们不愿意再次为您提供帮助.
2)请不要使用VS提供的默认名称:将其更改为更有意义的名称.您可能已经了解今天在"TextBox7"中应该包含的内容,但是下周可能会很模糊.称它为"inputUserName"或任何使您的代码更易读和易于维护的代码.
3)我的意思是关于Parameters.Add贬值,而赞成使用Parameters.AddWithValue.

Or better use TryParse to convert them, as you could then report a user error if he enters "Hello" instead of "123.45".
In addition, you should check your inputs: if the user puts "0" in TextBox12, then the code will throw a Divide by Zero exception.

BTW:
1) Deleting your question when it has been replied to is very rude, and can make people unwilling to help you again.
2) Please don''t use the default names that VS supplies: change them to something more meaningful. You may understand what is supposed to be in "TextBox7" today, but next week it may be a blur. Calling it "inputUserName" or whatever makes your code more readable, and easier to maintain.
3) I really meant it about Parameters.Add being depreciated in favour of Parameters.AddWithValue.


我怀疑您是否真的需要舍入.这很少需要.我怀疑您只需要获取字符串表示形式即可减少位数.

为此,请使用正确的格式:
I doubt you really need rounding. This is rarely needed. I suspect you simply need to obtain string presentation will less digits.

For this purpose, use proper format:
float value = 34.6789878;
//...
string number = value.ToString("F3");
string fortmatted = string.Format("Formatted value: {0:F3}", value);



—SA



—SA


这篇关于如何将浮点数减少到小数点后第2位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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