如何使用加号或减号来获取双C#的小数部分 [英] How to get the decimal part of a double C# with plus or minus symbol

查看:81
本文介绍了如何使用加号或减号来获取双C#的小数部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有但我需要如果小数部分小于0.5则结果包含减号( - )符号。如果小数部分大于等于0.5结果包含加号(+)符号。

我使用下面的代码,但它返回带有(+)符号的所有十进制数。



假设

456.45 [输出应该是-.45]

456.65 [输出应该是+.65]





提前感谢



我的尝试:



  double   value  = Convert.ToDouble(textBox5.Text); 
int result =( int )((十进制 1 )* 100 );

if ((result)< 0。 5
{
textBox6.Text = - + result.ToString();
}
else
{
textBox6.Text = + + result.ToString();
}

解决方案

尝试:

  double  d =  456  45 ; 
double x = d - Math.Truncate(d);
if (x < 0 5 )x = -x;
Console.WriteLine(x);


你将乘以100,然后将其与0.5比较!



  double   value  = Convert.ToDouble(textBox5.Text); 
int result =( int )((十进制 1 )* 100 );

if ((result)< 50)
{
textBox6.Text = - + result.ToString();
}
else
{
textBox6.Text = + + result.ToString();
}


学习调试代码。如果您单步执行456.45的结果中的内容?它是45,但你假设结果是0.45。当你%1时,你会得到余数(.45),然后乘以100得到45.我假设你这样做是为了使它成为一个有效的int,但是如果你要比较分数那么你就不能使用注意。



其次,不要对这种精度的分数使用double,使用十进制十进制是精确的,而double是你的数字的近似值。 />


  decimal   value  = Convert.ToDecimal(textBox5.Text); 
decimal result = value 1 ;

if (结果< 0 0.5米)


I have got but I need If decimal part is less then 0.5 result contains minus(-) symbol. and if decimal part is greater then equal 0.5 result contains plus (+) symbol.
I using following code but It returns all the decimal number with (+) symbol.

suppose
456.45 [output should be -.45 ]
456.65 [output should be +.65 ]


thanks in advance

What I have tried:

double value = Convert.ToDouble(textBox5.Text);
            int result = (int)(((decimal)value % 1) * 100);

            if ((result)<0.5)
            {
                textBox6.Text = "-" + result.ToString();
            }
            else
            {
                textBox6.Text = "+" + result.ToString();
            }

解决方案

Try:

double d = 456.45;
double x = d - Math.Truncate(d);
if (x < 0.5) x = -x;
Console.WriteLine(x);


You're multiplying by 100 and then comparing it to 0.5!

double value = Convert.ToDouble(textBox5.Text);
int result = (int)(((decimal)value % 1) * 100);

if ((result)<50)
{
textBox6.Text = "-" + result.ToString();
}
else
{
textBox6.Text = "+" + result.ToString();
}


Learn to debug your code. If you step through it what is in "result" for "456.45"? It is 45, yet you are assuming the result is 0.45. When you "% 1" something you get the remainder (.45) which you then multiply by 100 to get 45. I assume you are doing this to make it a valid int, but if you are comparing fractions then you can't use ints.

Secondly, don't use double for fractions with this kind of precision, use decimal as decimal is precise and double is an approximation of your number.

decimal value = Convert.ToDecimal(textBox5.Text);
decimal result = value % 1;

if (result < 0.5M)


这篇关于如何使用加号或减号来获取双C#的小数部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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