I am trying to round off below decimal number upto 4 decimal point. the below decimal no is
1.0715086071862673E+301 but when i am using Math.Round function.it's not working and returning same above no.please let me know how to round this no.
**code here:**
double s=2.0;
double ku = Math.Pow(s, 1000);
double jlk = Math.Round(ku, 4);
here depending on my logic i need only 1.0715 number.
Why do you round it ? Its a whole number anyway.
using System;
// referencing System.Numerics.dll
using System.Numerics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
BigInteger bigInt = new BigInteger(2);
bigInt = BigInteger.Pow(bigInt, 1000);
Console.Out.WriteLine(bigInt.ToString());
}
}
}
Double val = 1.0715086071862673E+301
Math.Round(val / (10 ^ 297), 0) * (10 ^ 297))
The answer is going to be 1.0715E+301 ...
if you want it to be 1.0715, you would do
Double val = 1.0715086071862673E+301
Math.Round(val / (10 ^ 297), 0)
Additonally
This will work, but I wanted to point out that the conversion rounds in the process. (Also, this is vb.net - I'm not positive whether CType is how you convert in C#)
CType(CType((val / (10 ^ 297)) + 0.5, Long), Double) //Yields 1.0716
CType(CType((val / (10 ^ 297)), Long), Double) //Yields 1.0715
Use an appropriate type i.e. BigDecimal, src here Arbitrary-Precision Decimals in C#
Related
I'm very new with C#.
I don't understand why is x = 1 and not 1.4.
Can please somebody explain me this?
double x = (double)(12 / 5 - 3 % 2);
Console.WriteLine(x);
Because this is NOT about double.
You are integer-executing
(12 / 5 - 3 % 2);
and THEN casting to double. If you want this to be about double, then make sure at least one of the numbers is a double. In your case just mark the literals as double.
(12d / 5d - 3d % 2d);
is all doubles. As long as one is a double, the operation happens as double - but your original case makes all the calculations, THEN casts to double. So they happen as integer.
You're doing integer math and then converting to double. 12 / 5 = 2, 3 % 2 = 1, and 2 - 1 = 1.
Welcome to stackoverflow! :)
The problem is that you are operating all int, and afterwards converting them to double.
You need to make sure that you are operating with doubles from the beginning.
Try out the code in here: https://dotnetfiddle.net/xaQjKL
using System;
public class Program
{
public static void Main()
{
// Doubles from the beggining
double d_twelve = 12.0;
double d_five = 5.0;
double x = (double)(d_twelve / d_five);
Console.WriteLine($"Using all doubles: {x}");
// First split two int, then convert the result to double
int i_twelve = 12;
int i_five = 5;
x = (double)(i_twelve / i_five);
Console.WriteLine($"Using ints, and converting at the end to double: {x}");
// And now your code:
x = (double)(12 / 5 - 3 % 2);
Console.WriteLine($"Your original code: {x}");
// And now your code fixed (notice the 12 => 12.0):
x = (double)(12.0 / 5 - 3 % 2);
Console.WriteLine($"Changing 12 by 12.0: {x}");
}
}
You are doing operations with integers and then casting he result to a double.
double x = (12d / 5d - 3d % 2d);
Console.WriteLine(x);
Adding d after a number will make it a double while adding f will make it a float.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types#real-literals
Because you use integer values inside the parenthesis, and the expression is calculated using integer math before being cast to double.
You can use a double value for the first value and it should be enough:
> double x = (12d / 5) - (3 % 2);
> Console.WriteLine(x);
1.4
This question already has answers here:
Why I cannot the get percentage by using Int
(9 answers)
Closed 6 years ago.
When I enter, in the Windows Calculator utility, "15036/18218*100=" it returns 82.53375782193435
What I really want is 17.47 (100 - 82.53), but that's beside the point at the moment.
With this code:
// Example: thisQty == 3182; totalQty == 18218
private string GetPercentage(int thisQty, int totalQty)
{
int diff = totalQty - thisQty; // this equates to 15036
double prcntg = (diff/totalQty)*100; // this equates to 0.0 for some reason
return string.Format("{0}%", prcntg);
}
...I'm getting 0.0 for the prcntg value. Why? ISTM that this is the same operation that I'm doing by hand in the Calculator utility. Why doesn't it return 82.53375782193435?
The dividing of 2 ints will be an int even if the correct mathematical answer is with a fraction.
In order to have it keep the decimal part you must divide with a number of a type that holds the fraction part (like double or decimal):
Console.WriteLine(GetPercentage(3182, 18218));
private string GetPercentage(int thisQty, int totalQty)
{
int diff = totalQty - thisQty; // this equates to 15036
double prcntg = (diff / (double)totalQty) * 100;
return string.Format("{0}%", prcntg);
}
BTW - it doesn't matter if you cast to double the diff or the totalQty - for both it will do the / operation returning a double - which means keeping the fraction part
You are using an integer value, (which doesn't store factional part), so cast it to double, or use the parameter type as double (my recommendation). Your operation, 15036/18218 resolves to, 0.82 and in an integer value that is stored as 0... Where finally 0 * 100 is going to resolve to 0 anyways and that is where you get the result.
Try this instead,
private string GetPercentage(double thisQty, double totalQty)
{
double diff = totalQty - thisQty; // this equates to 15036
double prcntg = (diff/totalQty) * 100.0; // this equates to 0.0 for some reason
return string.Format("{0}%", prcntg);
}
This would have the fractional part too and you will get the result.
Based on Gilad Green's answer, here is what I ended up with, which gives the value I ultimately want, and also rounds the value to an integer:
private string GetPercentage(int thisQty, int totalQty)
{
int diff = totalQty - thisQty;
double prcntg = (diff / (double)totalQty) * 100;
prcntg = 100 - prcntg;
int roundedPercent = Convert.ToInt32(prcntg);
return string.Format("{0}%", roundedPercent);
}
This question already has answers here:
Extremely basic division equation not working in c#
(3 answers)
Closed 9 years ago.
(5 / 15) * 1185 should give 395.
decimal Test = (5 / 15) * 1185;
This, however, returns 0. What am I doing wrong?
5 / 15 is an integer division and returns 0. Use 5m / 15m to force decimal.
m is the C# suffix to signify to the compiler that the number your wrote is a decimal, even if it looks like an int. You can use f for floats and d for doubles (or 5.0).
While on the topic of suffixes, there is also L for long but that wouldn't have helped your with your division because it is also an integer type.
5 // Int32
5L // Int64
5d // Double
5.0 // Double
5m // Decimal
5f // Single
You need to use floating point division, not integer division. You can get the correct result by making it a floating point number, or using m (to specify it as a decimal) behind the 15:
decimal Test = (5 / 15.0) * 1185;
or
decimal Test = (5 / 15m) * 1185;
You could also use a lambda expression :
Func<decimal, decimal, decimal, decimal> exp = (x, y, z) => (x / y) * z;
Console.WriteLine(exp(5, 15, 1185));
outputs:
394.999999
as you are expecting 395 you will need to use a Math.Round
Console.WriteLine(Math.Round(exp(5, 15, 1185), 1));
outputs: 395.0
5/15 is 0 because you are using integer division.
You can try use one of the following code:
decimal test = (5m / 15) * 1185
decimal test = ((decimal)5 / 15) * 1185
decimal test = (5.0 / 15) * 1185
The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal type does not eliminate the need for rounding but rather minimizes errors due to rounding.
Link: http://msdn.microsoft.com/en-us/library/364x0z75
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
c# - How do I round a decimal value to 2 decimal places (for output on a page)
how to return decimal with long rest after the point like that:
3.786444499963
to this:
3.787
its not just cut the points it also round the rest of the number
Math.Ceiling(3.786444499963 * 1000) / 1000;
But the generally accepted rounding of 3.786444499963 to three decimal places is 3.786. Why do you think otherwise?
Thus:
var round = Math.Round(3.786444499963m, 3, MidpointRounding.AwayFromZero);
Console.WriteLine(round == 3.786m); // prints true
If you want it to ALWAYS round up:
var round = Math.Round(3.786444499963m + 0.0005m, 3);
Console.WriteLine(round == 3.787m); // prints true
Do you see what I did there? I added 0.0005m to the input before using Math.Round. In general, to round x to n decimal places,
var round = Math.Round(x + 5m * Convert.ToDecimal(Math.Pow(10, -n - 1)), n);
Or, perhaps, to avoid the ugly double/decimal conversion:
int k = 1;
decimal value = 5m;
while(k <= n + 1) { value /= 10m; k++; }
var round = Math.Round(x + value, n);
There's an edge case you need to be aware of. What happens to 3.786? Should it be rounded up to 3.787 or remain at 3.786? You haven't specified what you want exactly, so I'll leave this edge case to you.
RoundUp(3.786444499963M, 3);
static decimal RoundUp(decimal dec, int precision)
{
decimal rounder = (decimal)(0.5 * Math.Pow(10, -precision));
return Math.Round(dec + rounder, precision);
}
I want a function that is passed an integer, and if that integer is over a certain value (1000 in my current case) I want to perform some division on it so I can ultimately return an abbreviation of the original integer.
For example:
1000 = 1
1001 = 1
1099 = 1
1100 = 1.1
1199 = 1.1
1200 = 1.2
10000 = 10
10099 = 10
10100 = 10.1
It's the division and rounding side of things that has been causing me problems.
What would be the most suitable method to give me the results above?
How about:
int dividedBy100 = x / 100; // Deliberately an integer division
decimal dividedBy1000 = dividedBy100 / 10m; // Decimal division
string result = dividedBy1000.ToString();
I would advise using decimal here rather than float or double, as you fundamentally want decimal division by 10.
An abbreviation is by definition rounded.
If you are looking for more precision why not use Double instead of Integer?
Here's a suggestion
double function(int number)
{
if (number >= 1000)
{
return (((double)number) / 1000);
}
}
Your examples seem to imply that you only want one decimal place of precision, so how about something like this:
Divide by 100
Cast to double (or float)
Divide by 10
The first division will truncate any trailing numbers less than 100 (the equivalent of a 100-base floor function), then casting to double and dividing by 10 will give you the single decimal place of precision you want.
if t is the original number, then
int a=t/100
float b=a/10
b should contain your answer
Some more code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
while (true)
{
string s;
s = Console.ReadLine();
int a = Convert.ToInt32(s);
a = a / 100;
float b = a / (float)10.0;
Console.WriteLine(b);
}
}
}
}
You should use modular (remainder) mathematics to do this. You don't need to involve the FPU (Floating Point Unit).
static string RoundAndToString(int value, int denominator)
{
var remainder = value % denominator;
value = (value - remainder) / denominator;
if (remainder == 0)
return value.ToString();
remainder = (remainder * 10) / denominator;
return string.Format("{0}{1}{2}", value, CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, remainder);
}
Since you just want to truncate the number, it makes sense to convert it to a string, remove the last two characters from the string, then divide by 10 to get the corresponding number.
Here is the algorithm in Ruby. (I don't have C# handy)
a = 1000 #sample number
-> 1000
b = a.to_s[0..-3] #a converted to a string, then taking all characters except the last two.
-> "10"
c = b.to_i / 10.0 # converts to float in correct power
-> 1.0
You then display "c" in whatever format you want using sprintf (or the C# equivalent using FormatNumber).
try
int MyNumber = 10100;
string MyString = ((int) MyNumber/1000).ToString() + (( MyNumber % 1000) > 99 ? "." + (((int)( MyNumber / 100 )) % 10).ToString() : "");