C# round a number to any arbitrary digit of a double [duplicate] - c#

This question already has answers here:
Round a double to x significant figures
(17 answers)
Round double in two decimal places in C#?
(8 answers)
Closed 1 year ago.
I am looking to round a double to any arbitrary digit to right or left of the decimal point.
Math.Round only works for digits to the right of the decimal point, and I need to be able to round to values the nearest 10s, 100s, 1000s, ...
Example of desired inputs/outputs:
Round(1234.56789, 0) == 1235
Round(1234.56789, -3) == 1234.568
Round(1234.56789, 3) == 1000
This problem differs from Round double in two decimal places in C#?
because I need to round values to positions to the left of the decimal point such as 1,2345,000 rounding to the nearest 10,000

If we take 10 to the power of the digit position, we can round the double to the arbitrary precision
public double RoundToDigit(double i, int digitPosition)
{
double precision = Math.Pow(10, digitPosition);
double result = Math.Round(i / precision, 0) * precision;
return result;
}

Related

C#: How to round a float to a defined amount of relevant digits? [duplicate]

This question already has answers here:
How do you round a number to two decimal places in C#?
(15 answers)
How can I round a Decimal value upto a precision so that the total number of digits doesnot cross 15?
(2 answers)
Closed 8 months ago.
How can I limit a float to a defined amount of digits? Let's say I want a precision of 4, then it should be:
14.49193 -> 14.49
1.449193 -> 1.449
0.449193 -> 0.4492
0.000449193 -> 0.0004492
I resolved it with this method, there may be a smoother solution.
public static float LimitDigits(float val,int digits) {
if (val == 0) return 0;
return (float)((val<1.0)?Math.Round(val,digits+(int)Math.Floor(-(Math.Log10(val)))):Math.Round(val, Math.Max(0,digits-(int)Math.Floor((Math.Log10(val)+1)))));
}

Differences in double and decimal calculations in C# [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 3 years ago.
I am getting different results for the double and decimal calculations...
double value1 = 280.585 - 280.50;
decimal value2 = Convert.ToDecimal(280.585) - Convert.ToDecimal(280.50);
Console.WriteLine(value1);
Console.WriteLine(value2);
Output:
Double:0.0849999999999795
Decimal:0.085
But how come int and long give the same results?
int value1 = 2+2;
long value2 = 2+2;
Console.WriteLine(value1);
Console.WriteLine(value2);
Output:
4
4
280.585 and 280.5 are both exactly representable as short decimal fractions, as is their difference.
Assuming double is represented as IEEE 754 64-bit binary floating point, the closest double to 280.585 is 280.58499999999997953636921010911464691162109375. 280.5 is exactly representable as a double. Their difference is 0.08499999999997953636921010911464691162109375.
In the case of the 2+2=4 calculation, all the numbers are exactly representable in either int or long so both should get the exact answer.

How to divide an int to receive a decimal? [duplicate]

This question already has answers here:
How can I divide two integers to get a double?
(9 answers)
Closed 7 years ago.
I'm trying to calculate the area of a sector but when I divide angleParse by 360 and times it by radiusParse, I will sometimes receive a output of 0.
What happens and where do I need to fix it? (Sorry, if this is a weird question but I started learning C# yesterday, also I just started using StackOverflow today)
Frostbyte
static void AoaSc()
{
Console.WriteLine("Enter the radius of the circle in centimetres.");
string radius = Console.ReadLine();
int radiusParse;
Int32.TryParse(radius, out radiusParse);
Console.WriteLine("Enter the angle of the sector.");
string sectorAngle = Console.ReadLine();
int angleParse;
Int32.TryParse(sectorAngle, out angleParse);
double area = radiusParse * angleParse / 360;
Console.WriteLine("The area of the sector is: " + area + "cm²");
Console.ReadLine();
}
You've encountered integer division. If a and b are int, then a / b is also an int, where the non-integer part has been truncated (i.e. everything following the decimal point has been cut off).
If you want the "true" result, one or more of the operands in your division needs to be a floating point. Either of the following will work:
radiusParse * (double)angleParse / 360;
radiusParse * angleParse / 360.0;
Note that it's not sufficient to cast radiusParse to double, because the / operator has higher precedence than * (so the integer division happens first).
Finally, also note that decimal in .NET is its own type, and is distinct from float and double.
I think if you divide it by 360.0 it will work.
Alternatively declare a variable of type decimal and set this to 360.
private decimal degreesInCirle = 360;
// Other code removed...
double area = radiusParse * angleParse / degreesInCirle;

Unexpected double value in c# [duplicate]

This question already has answers here:
Why does integer division in C# return an integer and not a float?
(8 answers)
Closed 9 years ago.
Today i come with a problem and not able to figure out what is the issue with this simple statement
I Tried
double d =1/4;
expected ans for me is 0.25 but in reality ans is 0.0 why so ??
And what should we do if statement is in terms of integer variables like this
double a =(a-b)/(d+e);
Because what you done is here integer division. 1 / 4 always give you 0 as a result regardless which type you assing it.
.NET has 3 type of division. From 7.7.2 Division operator
Integer division
Floating-point division
Decimal division
From Integer division part;
The division rounds the result towards zero, and the absolute value of
the result is the largest possible integer that is less than the
absolute value of the quotient of the two operands.
If you want to 0.25 as a result, you should define one of your values as a floating point.
You can use one of these;
double d = 1d / 4d;
double d = 1d / 4;
double d = 1 / 4d;
And what should we do if statement is in terms of integer variables
like this
double a =(a-b)/(d+e);
I assume your a, b, d and e are integers, you should use one of these then;
double a = (double)(a-b) / (double)(d+e);
double a = (a-b) / (double)(d+e);
double a = (double)(a-b) / (d+e);
double d =1d/4;
should work.
If you don't specify the type of your numbers, it is treated as Integer. And integer 1/4 will be zero.
Use this:
double d = (double) 1 / 4;
/ Operator (msdn)
When you divide two integers, the result is always an integer. For
example, the result of 7 / 3 is 2. To determine the remainder of 7 /
3, use the remainder operator (%). To obtain a quotient as a rational
number or fraction, give the dividend or divisor type float or type
double. You can assign the type implicitly if you express the dividend
or divisor as a decimal by putting a digit to the right side of the
decimal point.
Try this:
double d = 1.0 / 4.0;

Trimming a Float up to a certain decimal point [duplicate]

This question already has answers here:
How do I display a decimal value to 2 decimal places?
(19 answers)
Closed 9 years ago.
I need a way to round down a float up to a specific number of decimal places. Math.Round will round up if the number after the cut is larger than 6, and Math.Floor does not work with decimal places.
Basically if I have 2.566321, I want the code to return 2.56. The only way I know that this can be done is to convert the float to a string and use string.format but I would rather not do that if possible.
Thanks.
A brute force way might be to multiply by 10^n where n is the number of decimal places you want, cast to int (which does truncation rather than rounding), then cast back to float and divide by 10^n again.
visually:
2.566321 * 10^2 = 2.566321 * 100 = 256.6321
(int) 256.6321 = 256
(float) 256 / 10^2 = (float) 256 / 100 = 2.56
Quick attempt at the code:
public float Truncate(float value, int decimalPlaces) {
int temp = (int) (value * Math.Pow(10, decimalPlaces));
return (float) temp / Math.Pow(10, decimalPlaces);
}
I haven't tested this, but that should get you going.

Categories

Resources