Choose a factor dependant on a boolean value c#

252 views Asked by At
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 :(

2

There are 2 answers

5
D Stanley On BEST ANSWER

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.

2
clcto On

You could just use an if statement:

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