I want to receive the number after the decimal dot in the form of an integer. For example, only 05 from 1.05 or from 2.50 only 50 not 0.50
the best of the best way is:
var floatNumber = 12.5523;
var x = floatNumber - Math.Truncate(floatNumber);
result you can convert however you like
var decPlaces = (int)(((decimal)number % 1) * 100);
This presumes your number only has two decimal places.
(318.40d % 1) * 100
outputs 39.9999999999977
, you can use casting to get around the rounding error: var decPlaces = (int)(((decimal)number % 1) * 100);
–
Ayer There is a cleaner and ways faster solution than the 'Math.Truncate' approach:
double frac = value % 1;
Solution without rounding problem:
double number = 10.20;
var first2DecimalPlaces = (int)(((decimal)number % 1) * 100);
Console.Write("{0:00}", first2DecimalPlaces);
Outputs: 20
Note if we did not cast to decimal, it would output
19
.
Also:
- for
318.40
outputs:40
(instead of39
) - for
47.612345
outputs:61
(instead of612345
) - for
3.01
outputs:01
(instead of1
)
If you are working with financial numbers, for example if in this case you are trying to get the cents part of a transaction amount, always use the
decimal
data type.
Update:
The following will also work if processing it as a string (building on @SearchForKnowledge's answer).
10.2d.ToString("0.00", CultureInfo.InvariantCulture).Split('.')[1]
You can then use Int32.Parse
to convert it to int.
Better Way -
double value = 10.567;
int result = (int)((value - (int)value) * 100);
Console.WriteLine(result);
Output -
56
10.20
it will output 19
. See my answer. –
Ayer The simplest variant is possibly with Math.truncate()
double value = 1.761
double decPart = value - Math.truncate(value)
I guess this thread is getting old but I can't believe nobody has mentioned Math.Floor
//will always be .02 cents
(10.02m - System.Math.Floor(10.02m))
double fract(double x) { return x - System.Math.Floor(x); }
–
Bedazzle var result = number.ToString().Split(System.Globalization.NumberDecimalSeparator)[2]
Returns it as a string (but you can always cast that back to an int), and assumes the number does have a "." somewhere.
int last2digits = num - (int) ((double) (num / 100) * 100);
318.401567d
your solution outputs 0.401567
where 40
is expected. –
Ayer public static string FractionPart(this double instance)
{
var result = string.Empty;
var ic = CultureInfo.InvariantCulture;
var splits = instance.ToString(ic).Split(new[] { ic.NumberFormat.NumberDecimalSeparator }, StringSplitOptions.RemoveEmptyEntries);
if (splits.Count() > 1)
{
result = splits[1];
}
return result;
}
string input = "0.55";
var regex1 = new System.Text.RegularExpressions.Regex("(?<=[\\.])[0-9]+");
if (regex1.IsMatch(input))
{
string dp= regex1.Match(input ).Value;
}
In my tests this was 3-4 times slower than the Math.Truncate answer, but only one function call. Perhaps someone likes it:
var float_number = 12.345;
var x = Math.IEEERemainder(float_number , 1)
var d = 1.5;
var decimalPart = Convert.ToInt32(d.ToString().Split('.')[1]);
it gives you 5
from 1.5
:)
25
for 0.25
though –
Urbannai 50
from 2.50
–
Microparasite For example, only 05 from 1.05 or from 2.50 only 50 not 0.50
–
Microparasite You may remove the dot .
from the double you are trying to get the decimals from using the Remove()
function after converting the double to string so that you could do the operations required on it
Consider having a double _Double
of value of 0.66781
, the following code will only show the numbers after the dot .
which are 66781
double _Double = 0.66781; //Declare a new double with a value of 0.66781
string _Decimals = _Double.ToString().Remove(0, _Double.ToString().IndexOf(".") + 1); //Remove everything starting with index 0 and ending at the index of ([the dot .] + 1)
Another Solution
You may use the class Path
as well which performs operations on string instances in a cross-platform manner
double _Double = 0.66781; //Declare a new double with a value of 0.66781
string Output = Path.GetExtension(D.ToString()).Replace(".",""); //Get (the dot and the content after the last dot available and replace the dot with nothing) as a new string object Output
//Do something
My answer is based on a suspected use-case behind this question and people coming to this question.
The following example program will display a decimal value in a way that appears like a currency like 34.99 or 1.00 unless it has further precision, in which case it will display the whole precision like, 290.19882 or 128.00001
Please critique. Remember the design is for display.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(ConvertToString(5.00m));
Console.WriteLine(ConvertToString(5.01m));
Console.WriteLine(ConvertToString(5.99m));
Console.WriteLine(ConvertToString(5.000000191m));
Console.WriteLine(ConvertToString(5.000000191000m));
Console.WriteLine(ConvertToString(51028931298373.000000191000m));
}
public static string ConvertToString(decimal value)
{
decimal whole = Math.Truncate(value);
decimal fractional = value - whole;
return ConvertToString(whole, fractional);
}
public static string ConvertToString(decimal whole, decimal fractional)
{
if (fractional == 0m)
{
return $"{whole:F0}.00";
}
else
{
string fs = fractional.ToString("F28").Substring(2).TrimEnd('0');
return $"{whole:F0}.{fs}";
}
}
}
Results
5.00
5.01
5.99
5.000000191
5.000000191
51028931298373.000000191
Use a regex: Regex.Match("\.(?\d+)")
Someone correct me if I'm wrong here
Regex.Match
but I've received the following error when trying to get the value of the decimal ArgumentException was unhandled: parsing "\.(?\d+)" - Unrecognized grouping construct.
–
Epoch It is very simple
float moveWater = Mathf.PingPong(theTime * speed, 100) * .015f;
int m = (int)(moveWater);
float decimalPart= moveWater -m ;
Debug.Log(decimalPart);
Why not use int y = value.Split('.')[1];
?
The Split()
function splits the value into separate content and the 1
is outputting the 2nd value after the .
Int32.Parse((12.05123d.ToString("0.00").Split('.')[1]))
–
Ayer © 2022 - 2024 — McMap. All rights reserved.
decimal
,float
,string
, ...? – Marcellmarcellaint y = value.Split('.')[1];
? – There.
is different in some countries. – Transversal