简体   繁体   中英

Choose a factor dependant on a boolean value c#

Boolean Multiplier;
double Number;
double Value;
string Text;
Text = (Value * (1 + (Convert.ToInt32(Multiplier) / 2)).ToString(".0##");

This is the current code I have abstracted down to the general behaviour with the intended behaviour of Value being multiplied by 1.5 if Multiplier is true and Value staying the same if Multiplier is false.

However, this someone does not work although it worked without the division and I think it has to do with floats not being displayed correctly. So I wanted to ask wether I can use something like enums where I have two values and one of them gets chosen dependant on wether the boolean is true or false. Other ways are appreciated as well as advice on formatting decimal numbers on the side as I'm pretty new. If this is documented somewhere already, then I'm sorry but I did not found it :(

You could just use an if statement:

double val = Value;
if( Multiplier )
{
   val = val * 1.5;
}
Text = val.ToString( ".0##" );

You should (IMHO) not use the conversion from boolean to int (or any other type). It relies on either tacit knowledge of the conversion rules and/or looking up the documentation.

Your requirement is :

Text is Value multiplied by 1.5 if Multiplier is true and Value staying the same if Multiplier is false, converted to a string.

So why not just code it this way, using a standard ternary operator:

Text = (Multiplier ? Value * 1.5 : Value).ToString(".0##");

Or some variant if you don't like the reference to Value duplicated.

It's clear what the two possible outcomes are, and does not rely on the rules converting a non-numeric type to a numeric type, and does not fall prey to the integer-division trap that your current code does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM