Convert double to decimal

I have a problem converting from double to decimal:

 public class CartesianCoordinates
    {
        public int LatitudeHours { get; set;}
        public int LatitudeMinutes { get; set; }
        public int LatitudeSeconds { get; set; }
        public GeoDirectionLongtitude LongitudeDirection { get; set; }

        public int LongitudeHours { get; set; }
        public int LongitudeMinutes { get; set; }
        public int LongitudeSeconds { get; set; }
        public GeoDirectionLatitude LatitudeDirection { get; set; }
    }

public class DecimalCoordinates
    {
        public decimal Latitude { get; set; }
        public decimal Longitude { get; set; }
    }

CartesianCoordinates CartesianCoordinates=new CartesianCoordinates(){LatitudeHours =12,LatitudeMinutes =34,LatitudeSeconds=56 }

     converterDecimalCoordinates.Latitude = CartesianCoordinates.LatitudeHours + (CartesianCoordinates.LatitudeMinutes + (CartesianCoordinates.LatitudeSeconds / 60)) / 60;

Why am I getting 12? I want 12.55

+3
source share
5 answers

As a by-product of my discussion with David M and Daniel Bruckner under this answer and partially incorrect expression from myself under this answer of Adam , it became clear that, unfortunately, all the answers are only partially correct. What's happening:

// example (all  x, y, z ar ints):
Decimal d = x + y + z / 60M;

// is left to right evaluated as
Decimal d = x + y + (((Decimal) z) / 60M);

// when doing addition, this is what happens when you add integers and something else:
Decimal d = x + y + (int) (((Decimal) z) / 60M);

// which will yield a truncated result.

: 60M 60.0 , , ( ) , / /, OP.

, / , ( ) , , :

Decimal GetDecimalLatitude(Decimal latitudeHours, Decimal latitudeMinutes, Decimal latitudeSeconds)
{
    return latitudeHours + (latitudeMinutes + (latitudeSeconds / 60)) / 60;
}

. :

converterDecimalCoordinates.Latitude = GetDecimalLatitude(
    CartesianCoordinates.LatitudeHours, 
    CartesianCoordinates.LatitudeMinutes,
    CartesianCoordinates.LatitudeSeconds);
+3

( , ). 60 60m, , 60.0, ( ).

+9
Int32 x = 10;

Decimal y = x / 4;  // Performs an integer devision - result is 2.0
Decimal z = x / 4M; // Performs a decimal devision - result is 2.25

, . M , , , .

+7

12, int , , - int. - , , .

:, , - , , - lol

+3

As already mentioned, you have an integer on either side of your division. Thus, the result is also an integer (which will then be implicated in a decimal number for the left side). To solve this problem, one side of your division must be decimal, which will lead to decimal division. So just try this line of code:

converterDecimalCoordinates.Latitude = CartesianCoordinates.LatitudeHours + (CartesianCoordinates.LatitudeMinutes + (CartesianCoordinates.LatitudeSeconds / 60)) / (decimal)60;
+1
source

Source: https://habr.com/ru/post/1754577/


All Articles