[英]C# - How can I convert the string value to decimal places?
基本上,我創建了一種表格,我可以選擇不同的形狀,當選擇軌跡欄上的值時,它可以計算出圓形,三角形或正方形的面積和邊界長度。
這些值目前帶有很多小數位,我想設置單選按鈕來選擇是2位,3位還是4位小數。
private void sliderBar(object sender, EventArgs e)
{
textBox3.Text = trackBar1.Value.ToString();
if(circleButton.Checked == true)
{
textBox2.Text = (circle.getArea(trackBar1.Value)).ToString();
textBox1.Text = (circle.getBoundLength(trackBar1.Value)).ToString();
}
else if(squareButton.Checked == true)
{
textBox2.Text = (square.getArea(trackBar1.Value)).ToString();
textBox1.Text = (square.getBoundLength(trackBar1.Value)).ToString();
}
else
{
textBox2.Text = (triangle.getArea(trackBar1.Value)).ToString();
textBox1.Text = (triangle.getBoundLength(trackBar1.Value)).ToString();
}
if (decimalPlaces2Button.Checked == true)
{
TextBox2.Text = decimal.Round(textBox2, 2, MidpointRounding.AwayFromZero).ToDouble();
}
}
這是一個可行的解決方案,不會四舍五入您的電話號碼。
static double TakeDecimals(double value, int decimalCount)
{
var truncation = Math.Pow(10, decimalCount);
return Math.Truncate(value * truncation) / truncation;
}
叫像
var input=24.343545;
TakeDecimals(input, 2);//24.34
TakeDecimals(input, 3);//24.343
TakeDecimals(input, 4);//24.3435
UPDATE
對於您的情況,擁有一個字符串,可以在調用該方法之前執行Convert.ToDouble(yourString)
。
Math.Round(value, 2);
首先使用“ Convert.ToDecimal”將字符串轉換為十進制。 然后使用“ Math.Round”舍入十進制數字(2、3或4個小數位)。
decimal area;
textBox3.Text = trackBar1.Value.ToString();
if(circleButton.Checked == true)
{
area = circle.getArea(trackBar1.Value)
textBox2.Text = area.ToString();
textBox1.Text = (circle.getBoundLength(trackBar1.Value)).ToString();
}
else if(squareButton.Checked == true)
{
area = square.getArea(trackBar1.Value)
textBox2.Text = area.ToString();
textBox1.Text = (square.getBoundLength(trackBar1.Value)).ToString();
}
else
{
area = triangle.getArea(trackBar1.Value)
textBox2.Text = area.ToString();
textBox1.Text = (triangle.getBoundLength(trackBar1.Value)).ToString();
}
if (decimalPlaces2Button.Checked == true)
{
decimal number1 = Convert.ToDecimal(area);
decimal numWithTwoDecimalPlace = Math.Round(number1, 2);
TextBox2.Text = numWithTwoDecimalPlace.ToString();
}
else if (decimalPlaces3Button.Checked == true)
{
decimal number1 = Convert.ToDecimal(area);
decimal numWithTwoDecimalPlace = Math.Round(number1, 3);
TextBox2.Text = numWithTwoDecimalPlace.ToString();
}
您可以使用此:
decimal convertedValue;
decimal.TryParse(textBox2.Text,out convertedValue);
textBox2.Text = Math.Round(convertedValue, 2).ToString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.