vb.net 如何在 Visual Studio 中将输出值设置为 2 个小数位?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39827842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:05:15  来源:igfitidea点击:

How can I set an output value to 2 decimal places in Visual Studio?

vb.net

提问by Rob P

Im putting together a basic Gross Profit Calculator in Visual Studio and need the output to show as a £ value, ie to 2 decimal places.

我在 Visual Studio 中组装了一个基本的毛利润计算器,并且需要将输出显示为 £ 值,即保留 2 个小数位。

I have tried this so far:

到目前为止我已经尝试过这个:

String.Format("{0:0.00}", TextBox3.Text = CStr(sale))

where TextBox3 is the output for the calculation. However on using this, nothing happens and the box remains empty and I can't work out why!

其中 TextBox3 是计算的输出。然而,在使用它时,没有任何反应,盒子仍然是空的,我不知道为什么!

采纳答案by sachin

Your syntax is not correct, re-write your code this way:

您的语法不正确,请按以下方式重新编写代码:

TextBox3.Text = String.Format("{0:0.00}", sale)

The String.Format's result wasn't being assigned to anything.

String.Format的结果没有被分配到任何东西。

回答by Panagiotis Kanavos

The syntax is wrong, and besides, CStris just another way to format other types as a string. By using it you preventString.Formatfrom doing its job

语法是错误的,此外,CStr这只是将其他类型格式化为字符串的另一种方式。通过使用它,你可以阻止String.Format它的工作

I think you are looking for

我想你正在寻找

TextBox3.Text = String.Format("{0:0.00}", sale) 

Furthermore, built-in numeric types override ToStringand allow custom formatting as well. If saleis a float, double or decimal, you can write:

此外,内置数字类型也覆盖ToString并允许自定义格式。如果sale是浮点数、双精度数或十进制数,则可以这样写:

TextBox3.Text = sale.ToString("0.00")

or

或者

TextBox3.Text = sale.ToString("N2")