c# - 如何在c#中只显示小数点后2个空格

标签 c# crash decimal

所以我必须为类制作 BMI 计算器,但我只需要一些帮助。

  1. 当我运行我的程序时,输入 2 个值然后计算,它显示正确的答案,但小数点后有大约 8 位数字。

  2. 如果我输入除数字以外的任何输入,它会使我的程序崩溃,我该如何解决?

这是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void weightTxt_TextChanged(object sender, EventArgs e)
    {


    }

    private void button1_Click(object sender, EventArgs e)
    {
        double BMI = 0;
        double weight = 0;
        double height = 0;
        height = Double.Parse(heightTxt.Text);
        weight = Double.Parse(weightTxt.Text);
        // declaring and assigning 
        if (weight > 300 || weight < 10)
        {
            MessageBox.Show("Not a valid input.");

        }
        if (height > 2.2 || height < 0.2)
        {
            MessageBox.Show("Not a valid input.");
        }

        // checking that values meet parameters
        BMI = weight / (height * height);
        string result = Convert.ToString(BMI);
        resultLbl.Text = "Your BMI is : " + result;

最佳答案

要解决非数字输入的崩溃问题,您可以使用 Double.TryParse 而不是 Double.Parse:

if (!Double.TryParse(heightTxt.Text, out height)) {
    MessageBox.Show("Not a valid input.");
    return;
}

要解决显示到小数点后 2 位的问题,请使用 BMI.ToString("#.##"),正如其他人评论的那样

关于c# - 如何在c#中只显示小数点后2个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42332527/

相关文章:

c# - 如何避免多次硬编码方法调用

c# - 在 ASP.NET 中从 SQL 数据库输出一条记录的一个字段

multithreading - IBM Websphere Portal中的轮询portlet问题

java - 为什么这个 BigInteger 在输入 FFFFFFFF (8 F) 时显示不正确的结果

ruby-on-rails - postgres 中的小数列。有没有一种方法可以存储没有尾随零的值

Java 将字符串转换为十进制(ASCII)?

c# - jquery ajax 调用可以在本地主机上运行,​​但不能在实时服务器上运行

c# - 将 UInt32 转换为 Int32 : Different compiler results

iphone - 如何理解设备上的崩溃日志

visual-studio-2012 - 尝试更新、修复、卸载时 Visual Studio 2012 崩溃