How to round off decimals from string input and convert to int - c#

I would like my text entry to round off decimals and have the end result be an integer. This is what I have but it is not working. What would be the easiest way to do this? Thanks
decimal startMiles = Int32.Parse(txtStartMiles.Text);
startMiles = Math.Round(startMiles);
startMiles = Int32.Parse(startMiles);

int rounded;
string input = "2.53";
decimal startMiles;
if (Decimal.TryParse(input, out startMiles))
{
rounded = Convert.ToInt32(startMiles);
// here is rounded == 3
}
Convert.ToInt32 Method (Double)
Value is 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.

Related

How to trim decimal from double value in c#

I am trying to remove last digit from 1719.4703776041661 double value in c#. I would like to have only 12 digits in double value. How can i achieve this?
Tried following, but still getting same value as input (13 digits).
Math.Round(1719.4703776041661, 12) // Same Result with 13 digits
double.parse(value.ToString("N12"))
You are facing a precision problem. Check this:
double d = 1719.4703776041849;
Place a breakpoint and check the value stored in d, you will be surprised it doesn't match. That's because the number requires higher precision than what double offers.
If you need such precision then you must use decimal instead of double. This will work:
decimal d = 1719.4703776041661M; //Need the M suffix to denote a decimal value.
var z = Math.Round(d, 12); //It returns 1719.470377604166

converting int to decimal choosing where to put decimal place

I have an interesting problem, I need to convert an int to a decimal.
So for example given:
int number = 2423;
decimal convertedNumber = Int2Dec(number,2);
// decimal should equal 24.23
decimal convertedNumber2 = Int2Dec(number,3);
// decimal should equal 2.423
I have played around, and this function works, I just hate that I have to create a string and convert it to a decimal, it doesn't seem very efficient:
decimal IntToDecConverter(int number, int precision)
{
decimal percisionNumber = Convert.ToDecimal("1".PadRight(precision+1,'0'));
return Convert.ToDecimal(number / percisionNumber);
}
Since you are trying to make the number smaller couldn't you just divide by 10 (1 decimal place), 100 (2 decimal places), 1000 (3 decimal places), etc.
Notice the pattern yet? As we increase the digits to the right of the decimal place we also increase the initial value being divided (10 for 1 digit after the decimal place, 100 for 2 digits after the decimal place, etc.) by ten times that.
So the pattern signifies we are dealing with a power of 10 (Math.Pow(10, x)).
Given an input (number of decimal places) make the conversion based on that.
Example:
int x = 1956;
int powBy=3;
decimal d = x/(decimal)Math.Pow(10.00, powBy);
//from 1956 to 1.956 based on powBy
With that being said, wrap it into a function:
decimal IntToDec(int x, int powBy)
{
return x/(decimal)Math.Pow(10.00, powBy);
}
Call it like so:
decimal d = IntToDec(1956, 3);
Going the opposite direction
You could also do the opposite if someone stated they wanted to take a decimal like 19.56 and convert it to an int. You'd still use the Pow mechanism but instead of dividing you would multiply.
double d=19.56;
int powBy=2;
double n = d*Math.Pow(10, powBy);
You can try create decimal explictly with the constructor which has been specially designed for this:
public static decimal IntToDecConverter(int number, int precision) {
return new decimal(Math.Abs(number), 0, 0, number < 0, (byte)precision);
}
E.g.
Console.WriteLine(IntToDecConverter(2423, 2));
Console.WriteLine(IntToDecConverter(1956, 3));
Outcome:
24.23
1.956
Moving the decimal point like that is just a function of multiplying/dividing by a power of 10.
So this function would work:
decimal IntToDecConverter(int number, int precision)
{
// -1 flips the number so its a fraction; same as dividing below
decimal factor = (decimal)Math.Pow(10, -1*precision)
return number * factor;
}
number/percisionNumber will give you an integer which you then convert to decimal.
Try...
return Convert.ToDecimal(number) / percisionNumber;
Convert your method like as below
public static decimal IntToDecConverter(int number, int precision)
{
return = number / ((decimal)(Math.Pow(10, precision)));
}
Check the live fiddle here.

Extract the number after the decimal ponit in c# [duplicate]

This question already has answers here:
Double vs Decimal Rounding in C#
(2 answers)
Closed 5 years ago.
I should write a program that the input is double (variable called money), and I should print separately the digits before the decimal point and the digits after.
for example:
for the input: 36.5 should print: The number before the decimal point is: 36 The number after decimal point is: 5
for the input: 25.4 should print: The number before the decimal point is: 24 The number after decimal point is: 4
Console.WriteLine("Enter money:");
double money = double.Parse(Console.ReadLine());
int numBeforePoint = (int)money;
double numAfterPoint = (money - (int)money)*10;
Console.WriteLine("The number beforethe decimal point is: {0}. the number after the decimal point is: {1}",numBeforePoint,numAfterPoint);
If I enter 25.4 it prints: The number before the decimal point is: 24 The number after decimal point is: 3.9999999
I don't want 3.999999 I want 4
You should use decimal to represent numeric types, rather than doubles - it's what they were designed for!
You've been the victim of a floating point error, where the value you're assigning to a floating point value can't be exactly represented with its precision (the .999... you get is the closest value it can represent).
decimals have a lower range than doubles, but much higher precision - this means they're more likely to be able to represent the values you're assigning. See here or the linked decimal documentation page for more details.
Note that a more conventional way of getting the decimal part involves Math.Truncate (which by the way will work for negative values as well):
decimal numAfterPoint = (money - Math.Truncate(money))*10;
Probably easiest to use the string representation of the decimal, and use substring before and after the index of '.'
Something like this:
string money = Console.ReadLine();
int decimalIndex = money.IndexOf('.');
string numBeforePoint = money.Substring(0, decimalIndex);
string numAfterPoint = money.Substring(decimalIndex + 1);
Then you can parse the string representations as needed.
Try this:
static string Foo(double d)
{
var str = d.ToString(CultureInfo.InvariantCulture).Split('.');
var left = str[0];
var right = str[1];
return $"The number before the decimal point is: {left} The number after decimal point is: {right}";
}
using System.Linq;
public static string GetDecimalRemainder(double d)
{
return d.ToString(CultureInfo.InvariantCulture).Split('.').Last();
{
Using LINQ is much more convenient in my opinion.

How do I convert my string?

I have a string that can be up to 9 characters long including an optional decimal point but all the others will be numbers. It could be "123456789" or "12.345678", for example.
What variable type should I convert it to so that I can use it in calculations?
And how do I do that?
float.Parse("12.345678");
or
float.Parse("12.345678", CultureInfo.InvariantCulture.NumberFormat);
For avoiding these kind of outputs:
1.524157875019e+16
8.10000007371e-9
For integers you can checkout this link also: https://msdn.microsoft.com/en-us/library/bb397679.aspx
You should convert it to float, double or decimal, depending on how big the numbers become.
You can use Parse() or TryParse() to parse a string to an arithmetic type.
string numberString = "123456789";
double number;
if (!double.TryParse(numberString, out number))
{
// There was an error parsing ...
// Ex. report the error back or whatever ...
// You can also set a default value for it ...
// Ex. number = 0;
}
// Use number ...
It's a question of precision and a bit of memory consumption.
if the floating point remainder is important to you use one of the following:
float - 4 bytes, 7 digits precision
Double - 8 bytes, 15-16 digits precision
Decimal - 16 bytes , 28-29 digits precision

Round decimal value to nearest 5 or 0 amount

I have a web application that will apply a percentage markup to a product, but the percentage will be specified by a user. For example, the user can indicate they want to mark up a product 5%, 9%, 23%, etc. My problem is, the product price will change as well, and in doing so, end up giving ugly values ($1462.72)
As a result, my users are hoping that we can round the value to the nearest 5\0 value. So if my marked up product price is $1462.72, it would round up to $1465. $1798.02 on the other hand would round up to an even $1800.
Using VB\C#, how can I go about rounding these values?
Thanks!
To round to an arbitrary modulus you can create a function like:
public decimal Round(decimal source, decimal modulus)
{
return (Math.Round(source / modulus) * modulus);
}
and use it in this way:
decimal rounded = Round(1798.02m , 5.0m); // yields 1800.0
decimal rounded = Round(1462.72m , 5.0m); // yields 1465.0
decimal rounded = Round(2481.23m , 5.0m); // yields 2480.0
Note that Math.Round by default rounds midpoint values to the closest even number (e.g. 1.5 and 2.5 would both "round" to 2. In your case, the effect is that any numbers that are exactly between a 0 and 5 number (i.e. 2.5, 7.5) would be rounded to the closest 10:
decimal rounded = Round(1697.50m , 5.0m); // yields 1700.0
decimal rounded = Round(1702.50m , 5.0m); // yields 1700.0
If you want to always round UP on the midpoint just specify that in Round:
return (Math.Round(source / modulus, MidpointRounding.AwayFromZero) * modulus);
You can use the modulus operator to calculate the adjustment needed.
decimal price = 1798.02;
decimal adjustment = price % 5.0;
if(adjustment != 0) //so we don't round up already round numbers
{
price = (price - adjustment) + 5;
}
This will bring it up to the next multiple of 5.

Categories

Resources