I am developing a windows forms application.I need to do some conversions and round up the values.I need to round up the double value to nearest integer.For example 1.4 should be 1 and 1.6 should be 2 after applying round up.Please refer my code below.
double d = 51386933935386.5;
uint x = (uint)Math.Round(d, 0, MidpointRounding.AwayFromZero);
After round up I need the value value = 51386933935386.But I am getting some different value.
The max value of UInt is 4,294,967,295.
You need to keep it a double or a long
EDIT: Or ulong if you want to keep it unsigned
51386933935386 is longer than uint max value. Use next:
double d = 51386933935386.5;
long x = (long)Math.Round(d, 0, MidpointRounding.AwayFromZero);
Why not use `Math.Floor(d);' ?
double d = 51386933935386.5;
var result = Math.Floor(d);
// result = 51386933935386
It returns the number you need.
Update
Thanks to #HimBromBeere to point it out you can accomplish your task using the code below.
Use this code
double d = 51386933935386.5;
var x = Math.Round(d, 0, MidpointRounding.AwayFromZero);
var result = Convert.ToInt64(x);
Related
Please help me to understand the different between Convert and BitConverter. In the below example, the above two methods give me two different answer:
UInt64 x = 0x4028b0a3d70a3d71;
// Use Convert
double d = Convert.ToDouble(x); // d = 4.6231392352297441E+18
// Use BitConverter
byte[] xArray = BitConverter.GetBytes(x);
double d1 = BitConverter.ToDouble(xArray, 0); // d1 = 12.345
Thank you
These two methods are used for different purposes; Convert.ToDouble(x) is equivalent to a cast: (double)x; which can be useful if you need the integer value to be treated as a floating point value, say, for mathematical operations:
int x = 7;
Console.WriteLine(x / 3); // 2
Console.WriteLine(Convert.ToDouble(x) / 3); // 2.3333333333333335
Console.WriteLine((double)x / 3); // 2.3333333333333335
BitConverter class is useful if you want to transmit the value over the network as a series of bytes; you'd use the BitConverter.GetBytes() on the sending side, and BitConverter.ToOriginalType() on the receiving end:
double x = 12.345;
byte[] xArray = BitConverter.GetBytes(x);
// Send xArray to another system over the network
// ...on the receiving system, presuming same endianness:
double d1 = BitConverter.ToDouble(xArray, 0); // d1 = 12.345
Now, in your example, let's take a look at what happens to the value of x in both cases:
UInt64 x = 0x4028b0a3d70a3d71;
// Use Convert
double d = Convert.ToDouble(x); // d = 4.6231392352297441E+18
d is a cast of x to double; in decimal form, 0x4028b0a3d70a3d71 = 4,623,139,235,229,744,497 = 4.623139235229744497+18 in scientific notation. No magic here, it's pretty much what you'd expect to happen. Onward.
// Use BitConverter
byte[] xArray = BitConverter.GetBytes(x);
double d1 = BitConverter.ToDouble(xArray, 0); // d1 = 12.345
...what? well, let's see how the double type is stored in memory. According to IEEE 754 specification for double, the format is:
first bit is a sign bit (0 = positive; 1 = negative)
next 11 bits are the exponent
next 52 bits are the significand (well, 53, but only 52 are stored)
Here's the binary representation of 0x4028b0a3d70a3d71, arranged into the 3 sections we need to consider:
0 10000000010 1000101100001010001111010111000010100011110101110001
The following formula is used to convert this storage format to an actual numeric value:
(-1)sign x (1.b51b50...b0)base2 x 2exponent - 1023
Instead of going through this math manually, we can use this awesome floating point converter; here's the snapshot of the result:
See the decimal result? 12.345, same as what you're getting with BitConverter.ToDouble(xArray, 0) - but certainly not the same as the casting operation performed by Convert.ToDouble(x)
The first:
you convert int hex representation to double
The second:
you treat the value in x as a bit representation of a double, not integer.
Lets say I have the double 42.433243 and I would like to convert it to the integer 42433243.
What is the code for doing that when the decimal length is random?
Further examples:
45.25 => 4525
125.152254 => 125152254
etc...
You can multiply the value by 10 as long as there are any fraction part:
Decimal m = 42.433243m;
while (m % 1 != 0) m *= 10;
int i = (int)m;
Quick and dirty:
double x = 42.25;
int big = int.Parse(x.ToString().Replace(".",""));
This doesn't work if the number is too big (e.g. overflow, bigger than 2^32 for int, or you could replace int with double on line 2 and get it a lot larger).
Let me know if you have other considerations.
Perhaps something like this would work.
while ((double_num - Math.floor(double_num)) != 0.0) double_num *= 10;
int num = (int) double_num;
int result = Convert.ToInt32(Regex.Match(digits.Replace(".","").Replace(",",""), #"^\d+$").Value);
A more direct way to do this would be to convert the number to a decimal and examine the bits.
The first 96 least-significant bits represents the mantissa while the 32 most-significant bits represents the exponent. So the actual value that you would be interested in is the 32 least significant bits. The Decimal.GetBits() method returns the bits as an array ints so all you need to do is grab the first int in the array. As long as the numbers don't exceed int.MaxValue, you're golden.
var number = 42.433243;
var asDecimal = (Decimal)number;
var bits = Decimal.GetBits(asDecimal);
var digits = bits[0]; // 42433243
I have a database with a table, containing two integer fields.
When I try to get a percentage (fieldA / (fieldA+fieldB)), the value is 0.
double percentage = fieldA+fieldB // WORKS; 5+5=10
double percentage = fieldA / (fieldA+fieldB) // DOES NOT WORK; 5+5=0
So what's the problem here? Thanks..
When you do fieldA / (fieldA+fieldB) you get 5/10, which as an integer is truncated to 0, you have to do double division if you want 0.5 as a result.
i.e. something like this:
double percentage = (double)fieldA/(fieldA+fieldB)
I do assume fieldA and fieldB are integers? If yes, you should be aware that dividing two integers results in an integer, too, no matter what is on the left side of the equation.
So dividing fieldA by (fieldA+fieldB) results in a value < 1 which results in zero. See Integer Division on Wikipedia.
To correct the issue, simply cast at least one operand to a floating point type like e.g.:
double percentage = fieldA/(double)(fieldA+fieldB)
Since fieldA and fieldB are integers, the expression fieldA / (fieldA+fieldB)is of the form int / int which means you will use integer division, in this case - 5/10 = 0, as integer division solves x = am + b, and in this case 5 = a*10 + b which means a = 0, b = 5
You can do however:
double percentage = (double)fieldA / (fieldA+fieldB);
You may need to cast the fields as doubles before applying the operation
try this : double percentage = (double)fieldA/(double)(fieldA+fieldB)
if both fields are integer, then the addition of the two integer results also integer.
Try this
float result = (float)((A*100)/(B+A));
Answer: result = 50.0
How can I round values to nearest integer?
For example:
1.1 => 1
1.5 => 2
1.9 => 2
"Math.Ceiling()" is not helping me. Any ideas?
See the official documentation for more. For example:
Basically you give the Math.Round method three parameters.
The value you want to round.
The number of decimals you want to keep after the value.
An optional parameter you can invoke to use AwayFromZero rounding. (ignored unless rounding is ambiguous, e.g. 1.5)
Sample code:
var roundedA = Math.Round(1.1, 0); // Output: 1
var roundedB = Math.Round(1.5, 0, MidpointRounding.AwayFromZero); // Output: 2
var roundedC = Math.Round(1.9, 0); // Output: 2
var roundedD = Math.Round(2.5, 0); // Output: 2
var roundedE = Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // Output: 3
var roundedF = Math.Round(3.49, 0, MidpointRounding.AwayFromZero); // Output: 3
Live Demo
You need MidpointRounding.AwayFromZero if you want a .5 value to be rounded up. Unfortunately this isn't the default behavior for Math.Round(). If using MidpointRounding.ToEven (the default) the value is rounded to the nearest even number (1.5 is rounded to 2, but 2.5 is also rounded to 2).
Math.Ceiling
always rounds up (towards the ceiling)
Math.Floor
always rounds down (towards to floor)
what you are after is simply
Math.Round
which rounds as per this post
You need Math.Round, not Math.Ceiling. Ceiling always "rounds" up, while Round rounds up or down depending on the value after the decimal point.
there's this manual, and kinda cute way too:
double d1 = 1.1;
double d2 = 1.5;
double d3 = 1.9;
int i1 = (int)(d1 + 0.5);
int i2 = (int)(d2 + 0.5);
int i3 = (int)(d3 + 0.5);
simply add 0.5 to any number, and cast it to int (or floor it) and it will be mathematically correctly rounded :D
You can use Math.Round as others have suggested (recommended), or you could add 0.5 and cast to an int (which will drop the decimal part).
double value = 1.1;
int roundedValue = (int)(value + 0.5); // equals 1
double value2 = 1.5;
int roundedValue2 = (int)(value2 + 0.5); // equals 2
Just a reminder. Beware for double.
Math.Round(0.3 / 0.2 ) result in 1, because in double 0.3 / 0.2 = 1.49999999
Math.Round( 1.5 ) = 2
You have the Math.Round function that does exactly what you want.
Math.Round(1.1) results with 1
Math.Round(1.8) will result with 2.... and so one.
this will round up to the nearest 5 or not change if it already is divisible by 5
public static double R(double x)
{
// markup to nearest 5
return (((int)(x / 5)) * 5) + ((x % 5) > 0 ? 5 : 0);
}
I was looking for this, but my example was to take a number, such as 4.2769 and drop it in a span as just 4.3. Not exactly the same, but if this helps:
Model.Statistics.AverageReview <= it's just a double from the model
Then:
#Model.Statistics.AverageReview.ToString("n1") <=gives me 4.3
#Model.Statistics.AverageReview.ToString("n2") <=gives me 4.28
etc...
Using Math.Round(number) rounds to the nearest whole number.
Use Math.Round:
double roundedValue = Math.Round(value, 0)
var roundedVal = Math.Round(2.5, 0);
It will give result:
var roundedVal = 3
If your working with integers rather than floating point numbers, here is the way.
#define ROUNDED_FRACTION(numr,denr) ((numr/denr)+(((numr%denr)<(denr/2))?0:1))
Here both "numr" and "denr" are unsigned integers.
Write your own round method. Something like,
function round(x)
rx = Math.ceil(x)
if (rx - x <= .000001)
return int(rx)
else
return int(x)
end
decimal RoundTotal = Total - (int)Total;
if ((double)RoundTotal <= .50)
Total = (int)Total;
else
Total = (int)Total + 1;
lblTotal.Text = Total.ToString();
I want get integer quotient when I divide two values. Per example
X=3
Y=2
Q=X/Y = 1.5 // I want get 1 from results
X=7
Y=2
Q=X/Y=3.5 //I want get only 3 from results
Integer math is going to do this for you.
int x = 3 / 2; // x will be 1
int y = 7 / 2; // y will be 3
int z = 7 % 2; // z will be 1
If you were using decimal or floating-point values in your equations, that would be different. The simplest answer is to cast the result to an int, but there are static Math functions you could also use.
double a = 11d;
double b = 2d;
int c = (int)(a / b); // showing explicit cast, c will be 5
Try Math.Truncate. This should do it.
In VB.NET there is the integer division operator (\). It returns only the integer portion of the division. This comes all the way from the original Dartmouth BASIC so it exists in most forms of BASIC.
try Math.Floor()
There is another elegant way of getting quotient and remainder in .NET using Math.DivRem() method which takes 2 input parameter, 1 output parameter and returns integer.
using System;
For dividend: 7 and divisor: 2
To get only quotient(q)
int q = Math.DivRem(7, 2, _);
//requires C# >= 7.0 to use Discards( _ )
To get quotient(q) and remainder(r)
int q = Math.DivRem(7, 2, out int r);
Math.DivRem() has 2 overloads for 32-bit and 64-bit signed integers.
try using simple maths
int X = 10 ;
int Y = 3 ;
int Q = ( X - ( X % Y ) ) / Y ; // ( it will give you the correct answer )
It works by subtracting the remainder beforehand from the first number so that we don't get a remainder at all !