Pizhev Racing
Pizhev Racing

Reputation: 486

Error CS0019: Operator '*' cannot be applied to operands of type 'decimal' and 'double' (CS0019)

I want to use Math.Round function on one object who come double?. I try to convert to decimal and after to use math.round function but I receive this error:

Error CS0019: Operator '*' cannot be applied to operands of type 'decimal' and 'double' (CS0019) (WeatherLocationInfo)

My code is:

double? wSpeedInputFirstDay = weatherBindingData.WeatherDataForecastHourly.List[0].WindForecast.WindForecastValue;
decimal wSpeedOutPutFirstDay = Convert.ToDecimal(wSpeedInputFirstDay);

string wSpeedFirstDay = $"{Math.Round(wSpeedOutPutFirstDay) * 3.6:0}km/h";

When I try directly to use Math.Round with the double? object like this:

double? wSpeedInputFirstDay = weatherBindingData.WeatherDataForecastHourly.List[0].WindForecast.WindForecastValue;

string wSpeedFirstDay = $"{Math.Round(wSpeedInputFirstDay) * 3.6:0}km/h";

I receive this error:

Error CS1503: Argument 1: cannot convert from 'double?' to 'decimal' (CS1503) (WeatherLocationInfo)

How is the correct way to use the function Math.Round on double? object?

Upvotes: 1

Views: 2440

Answers (2)

Eric Wu
Eric Wu

Reputation: 917

First: Math.Round will either output a double or a decimal, depending on the input. On the first sample, it returned decimal because wSpeedOutPutFirstDay is one. On the second, wSpeedInputFirstDay is declared as double?, so double it outputs.

That said, the way you declared your 3.6 value defines the type it outputs to.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types#real-literals

If you want to declare 3.6 as decimal, use it like that: 3.6m or 3.6M. If you want 3.6 to be float, use 3.6F. Declaring it the way you did (3.6) types it as double.

The reason the compiler throws an exception is that there are no built-in * operators that accept two different types. Unless you add them, the best option is to use the same type for both values.

Upvotes: 3

David Mkheyan
David Mkheyan

Reputation: 528

You can try it this way.

double? wSpeedInputFirstDay =weatherBindingData.WeatherDataForecastHourly.List[0].WindForecast.WindForecastValue;
decimal wSpeedOutPutFirstDay = Convert.ToDecimal(wSpeedInputFirstDay);
string wSpeedFirstDay = $"{Math.Round(wSpeedOutPutFirstDay) * 3.6m:0}km/h";

Upvotes: 3

Related Questions