In C#, I have a long that I need to convert to a decimal. The problem is that I want to put the decimal point at a specific position in the long.
For example, let's say I have the following number as a long:
long l = 123456789
When converting to a decimal with the floating point at the third position, I want to have the following:
decimal d = 123456.789
To give you an example, the function would ideally be something like the BigDecimal.valueOf in Java that allows you to give a long and a position to put the decimal point, and it returns the correct value.
I know one of the solution would be to format the long as a string with the correct decimal point position and then convert it back to a decimal. Another solution would be to multiply the long by 10-Decimal places wanted, but I'm wondering if there's a better alternative to this.
Why don't you divide by 1000 (or 10^N where N is the number of decimal places)?
long l = 123456789L;
int decplaces = 3;
decimal divisor =(decimal) Math.Pow(10, decplaces);
decimal d = l/divisor;
You could use the Decimal constructor that takes different constituent parts. You'll need to do a bit of bitshifting to get the exponent into all the relevant sections, but that shouldn't be too hard. If you know that your value won't be more than 62 bits in magnitude, that would make things easier, too.
You could just write a loop to multiply by 0.1m the correct number of times, i.e. numberOfDecimalPlacesWanted iterations of the loop.
Related
I have a problem to round a number to two decimal places.
I have the number 3106.4647771976413339683766317M.
The correct round to two decimal places is 3106.47, but using Math.Round(value, 2, MidpointRounding.AwayFromZero) the number is 3106.46.
The problem is the method look to third decimal place to round, but if it look to fourth decimal place will generate the correct number.
Someone has something like that?
Mathematically, the correct round to two decimal places is 3106.46.
What you probably want is a ceiling:
Math.Ceiling(3106.4647771976413339683766317M * 100) / 100
produces 3106.47. There is no version of Math.Ceiling accepting a number of decimal places, that's why there are multiplication and division.
In addition, note that there is a caveat in this expression:
Math.Round(value, 2, MidpointRounding.AwayFromZero)
Math.Round does not have a variant with three arguments, where the first one is a decimal. It works, because the value is implicitly converted to double. However, this is unwanted.
If you really want to round that way (more of a common mistake than actual rounding in the traditional sense) you can round up from the furthest right digit and move left one place at a time.
double numberToRound = 3106.4647771976413339683766317;
int placesToRoundTo = 2;
int smallestPlaceIndex = 24; // you would need to determine this value
for (int i = smallestPlaceIndex; i >= placesToRoundTo)
{
numberToRound = Math.Round(numberToRound, i, MidpointRounding.AwayFromZero);
}
There isn't a simple built-in method to do this because it isn't normal rounding.
I have number of type double.
double a = 12.00
I have to make it as 12 by removing .00
Please help me
Well 12 and 12.00 have exactly the same representation as double values. Are you trying to end up with a double or something else? (For example, you could cast to int, if you were convinced the value would be in the right range, and if the truncation effect is what you want.)
You might want to look at these methods too:
Math.Floor
Math.Ceiling
Math.Round (with variations for how to handle midpoints)
Math.Truncate
If you just need the integer part of the double then use explicit cast to int.
int number = (int) a;
You may use Convert.ToInt32 Method (Double), but this will round the number to the nearest integer.
value, rounded to the nearest 32-bit signed integer. If value is
halfway between two whole numbers, the even number is returned; that
is, 4.5 is converted to 4, and 5.5 is converted to 6.
Use Decimal.Truncate
It removes the fractional part from the decimal.
int i = (int)Decimal.Truncate(12.66m)
Use Math.Round
int d = (int) Math.Round(a, 0);
Reading all the comments by you, I think you are just trying to display it in a certain format rather than changing the value / casting it to int.
I think the easiest way to display 12.00 as "12" would be using string format specifiers.
double val = 12.00;
string displayed_value = val.ToString("N0"); // Output will be "12"
The best part about this solution is, that it will change 1200.00 to "1,200" (add a comma to it) which is very useful to display amount/money/price of something.
More information can be found here:
https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx
here is a trick
a = double.Parse(a.ToString().Split(',')[0])
Because the numbers after point is only zero, the best solution is to use the Math.Round(MyNumber)
//I am doing a basic Calculation here and this works for me.
// it takes values from textboxes and performs the following as far as I understand it. as I have only been coding now for a few months.
double VC2 = Convert.ToDouble(txt_VC_M16_Tap.Text); // converts to double.
double total2 = (VC2 * 1000) / (3.14157 * 14.5); // performs the calculation.
total2 = Math.Round(total2); //Round the result to a whole number(integer)
txt_RPM2.Text = Convert.ToString(total2); // converts result to string and puts it in the textbox as required.
// Hope this helps people that are looking for simple answers.
This i what I am trying to achieve:
If a double has more than 3 decimal places, I want to truncate any decimal places beyond the third. (do not round.)
Eg.: 12.878999 -> 12.878
If a double has less than 3 decimals, leave unchanged
Eg.: 125 -> 125
89.24 -> 89.24
I came across this command:
double example = 12.34567;
double output = Math.Round(example, 3);
But I do not want to round. According to the command posted above,
12.34567 -> 12.346
I want to truncate the value so that it becomes: 12.345
Doubles don't have decimal places - they're not based on decimal digits to start with. You could get "the closest double to the current value when truncated to three decimal digits", but it still wouldn't be exactly the same. You'd be better off using decimal.
Having said that, if it's only the way that rounding happens that's a problem, you can use Math.Truncate(value * 1000) / 1000; which may do what you want. (You don't want rounding at all, by the sounds of it.) It's still potentially "dodgy" though, as the result still won't really just have three decimal places. If you did the same thing with a decimal value, however, it would work:
decimal m = 12.878999m;
m = Math.Truncate(m * 1000m) / 1000m;
Console.WriteLine(m); // 12.878
EDIT: As LBushkin pointed out, you should be clear between truncating for display purposes (which can usually be done in a format specifier) and truncating for further calculations (in which case the above should work).
I can't think of a reason to explicitly lose precision outside of display purposes. In that case, simply use string formatting.
double example = 12.34567;
Console.Out.WriteLine(example.ToString("#.000"));
double example = 3.1416789645;
double output = Convert.ToDouble(example.ToString("N3"));
Multiply by 1000 then use Truncate then divide by 1000.
If your purpose in truncating the digits is for display reasons, then you just just use an appropriate formatting when you convert the double to a string.
Methods like String.Format() and Console.WriteLine() (and others) allow you to limit the number of digits of precision a value is formatted with.
Attempting to "truncate" floating point numbers is ill advised - floating point numbers don't have a precise decimal representation in many cases. Applying an approach like scaling the number up, truncating it, and then scaling it down could easily change the value to something quite different from what you'd expected for the "truncated" value.
If you need precise decimal representations of a number you should be using decimal rather than double or float.
You can use:
double example = 12.34567;
double output = ( (double) ( (int) (example * 1000.0) ) ) / 1000.0 ;
Good answers above- if you're looking for something reusable here is the code. Note that you might want to check the decimal places value, and this may overflow.
public static decimal TruncateToDecimalPlace(this decimal numberToTruncate, int decimalPlaces)
{
decimal power = (decimal)(Math.Pow(10.0, (double)decimalPlaces));
return Math.Truncate((power * numberToTruncate)) / power;
}
In C lang:
double truncKeepDecimalPlaces(double value, int numDecimals)
{
int x = pow(10, numDecimals);
return (double)trunc(value * x) / x;
}
I have a number with a variable number of digits after the decimal point. I want to format the number with commas and all decimal numbers.
For example: 42,023,212.0092343234
If I use ToString("N") I get only 2 decimals, ToString("f") gives me all decimals no commas. How do I get both?
Not sure (and unable to test right now) but would something like this work?
"#,##0.################"
string.Format("{0:#,##0.############}", value);
will give you up to 12 decimal places.
There is not a custom format specifier for "all following digits", so something like this will be closest to what you want.
Note too that you're limited by the precision of your variable. A double only has 15-16 digits of precision, so as your left-hand side gets bigger the number of decimal places will fall off.
UPDATE: Looking at the MSDN documentation on the System.Double type, I see this:
By default, a Double value contains 15
decimal digits of precision, although
a maximum of 17 digits is maintained
internally.
So I think pdr's on to something, actually. Just do this:
// As long as you've got at least 15 #s after the decimal point,
// you should be good.
value.ToString("#,#.###############");
Here's an idea:
static string Format(double value)
{
double wholePart = Math.Truncate(value);
double decimalPart = Math.Abs(value - wholePart);
return wholePart.ToString("N0") + decimalPart.ToString().TrimStart('0');
}
Example:
Console.WriteLine(Format(42023212.0092343234));
Output:
42,023,212.00923432409763336
Ha, well, as you can see, this gives imperfect results, due (I think) to floating point math issues. Oh well; it's an option, anyway.
Try ToString("N2")
Let's try this
[DisplayFormat(DataFormatString = "{0:0,0.00}")]
Here is the way somewhat to reach to your expectation...
decimal d = 42023212.0092343234M;
NumberFormatInfo nfi = (NumberFormatInfo) CultureInfo.InvariantCulture.NumberFormat.Clone();
nfi.NumberDecimalDigits= (d - Decimal.Truncate(d)).ToString().Length-2;
Console.WriteLine(d.ToString("N",nfi));
For more detail about NumberFormatInfo.. look at MSDN ..
http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx
Does anyone know of an elegant way to get the decimal part of a number only? In particular I am looking to get the exact number of places after the decimal point so that the number can be formatted appropriately. I was wondering if there is away to do this without any kind of string extraction using the culture specific decimal separator....
For example
98.0 would be formatted as 98
98.20 would be formatted as 98.2
98.2765 would be formatted as 98.2765 etc.
It it's only for formatting purposes, just calling ToString will do the trick, I guess?
double d = (double)5 / 4;
Console.WriteLine(d.ToString()); // prints 1.75
d = (double)7 / 2;
Console.WriteLine(d.ToString()); // prints 3.5
d = 7;
Console.WriteLine(d.ToString()); // prints 7
That will, of course, format the number according to the current culture (meaning that the decimal sign, thousand separators and such will vary).
Update
As Clement H points out in the comments; if we are dealing with great numbers, at some point d.ToString() will return a string with scientific formatting instead (such as "1E+16" instead of "10000000000000000"). One way to overcome this probem, and force the full number to be printed, is to use d.ToString("0.#"), which will also result in the same output for lower numbers as the code sample above produces.
You can get all of the relevant information from the Decimal.GetBits method assuming you really mean System.Decimal. (If you're talking about decimal formatting of a float/double, please clarify the question.)
Basically GetBits will return you 4 integers in an array.
You can use the scaling factor (the fourth integer, after masking out the sign) to indicate the number of decimal places, but you should be aware that it's not necessarily the number of significant decimal places. In particular, the decimal representations of 1 and 1.0 are different (the former is 1/1, the latter is 10/10).
Unfortunately, manipulating the 96 bit integer is going to require some fiddly arithmetic unless you can use .NET 4.0 and BigInteger.
To be honest, you'll get a simpler solution by using the built in formatting with CultureInfo.InvariantCulture and then finding everything to the right of "."
Just to expand on the point about getbits, this expression gets the scaling factor from a decimal called foo:
(decimal.GetBits(foo)[3] & 16711680)>>16
You could use the Int() function to get the whole number component, then subtract from the original.