How to get selected number after decimal point - c#

I have a double value for Example
0.0070
0.100
0.040
and I want output of above numbers as follows
70
100
40
Please guide me
Thanks

In theory this would be the way to do it
double number = 0.0070
string num = number.ToString(); //Convert to string
int index = num.IndexOf('.') + 1; //Find the decimal
string trunc = num.Substring(index); //Get rid of everything before it
trunc.TrimStart('0'); //Get rid of leading zeros
double result = Convert.ToDouble(trunc); //Convert back to double
However, C# does not respect trailing zeros in numerical values so as soon as you say 0.0070 into a double it is truncated to 0.007

public int getTheNumberAfterDecimalPoint(double number)
{
string numberInString = Convert.ToString(number);
if(numberInString.Contains('.'))
{
return Convert.ToInt32(numberInString.Substring('.')[1]);
}
return Convert.ToInt32(number);
}

Related

Convert double to long without truncating

How to convert a double to a long without truncating it?
For example,
I want -26.3999745 to become -263999745
So far the methods I have tried such as Convert.ToInt64() truncate the number.
EDIT:
The number of decimal places varies, some of the numbers may have 5 decimal places
If you are really sure this is what you really want ..
long.Parse((-26.3999745).ToString().Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator.ToString(), string.Empty)))
Following 2 steps
Get the numbers after the decimal n
Multiply by 10^n
Code:
double number = -26.3999745;
int n = BitConverter.GetBytes(decimal.GetBits((decimal)number)[3])[2];
long result = (long)(number * Math.Pow(10, n));
If you like to follow Single Responsibility (you should), then you can go with a second approach that is also not culture specific:
static int GetCountAfterDecimal(double number)
{
int count = 0;
string seperator = System.Globalization.CultureInfo.CurrentCulture
.NumberFormat.NumberDecimalSeparator;
string numberAsString = number.ToString();
int indexOfSeperator = numberAsString.IndexOf(seperator);
if (indexOfSeperator >= 0)
count = numberAsString.Length - indexOfSeperator - 1;
return count;
}
static long RemoveDecimalPoint(double number, int numbersCountAfterDecimal)
{
return (long)(number * Math.Pow(10, numbersCountAfterDecimal));
}
static void Main(string[] args)
{
double number = -26.3999745;
long result = RemoveDecimalPoint(number, GetCountAfterDecimal(number));
Console.WriteLine(result);
}
This might do the trick for you
double YourNumber = -26.3999745;
int DecimalPlacesCount = BitConverter.GetBytes(decimal.GetBits(Convert.ToDecimal(YourNumber))[3])[2];
long number = Convert.ToInt64("1".PadRight(DecimalPlacesCount + 1, '0'));
long kajs = (long) (YourNumber * number);

How to format floating point value with fix number of digits?

Is it possible in C# to format a double value with double.ToString in a way that I have always a fixed number of digits, no matter on which side of the decimal point?
Say I wish 6 digits, I want to have these results:
0.00123456789 gives "0.00123"
1.23456789 gives "1.23457"
123.456789 gives "123.457"
0.0000000123456789 gives "0.00000"
12345678.9 gives "12345679" (on overflow I want to see all digits left of decimalpoint)
4.2 gives "4.20000"
I'm experimenting with double.ToString, but cannot find any suitable format string.
Already tried "G6" (gives sometimes exponential format), "F6" (comes close, but 0.123456789 gives "0.123457" which are 7 digits).
I think some of your examples are wrong.
But I still think that I understand what you want to achieve.
I made an extension method.
public static class StringExtensionMethods
{
public static string ToString(this double d, int numberOfDigits)
{
var result = "";
// Split the number.
// Delimiter can vary depending on locale, should consider this and not use "."
string[] split = d.ToString().Split(new string[] { "." }, StringSplitOptions.None);
if(split[0].Count() >= numberOfDigits)
{
result = split[0].Substring(0, numberOfDigits);
}
else
{
result = split[0];
result += ".";
result += split[1];
// Add padding.
while(result.Count() < numberOfDigits +1)
result += "0";
result = result.Substring(0, numberOfDigits + 1);
}
return result;
}
}
I ran it with your examples:
double d0 = 0.00123456789;
double d1 = 1.23456789;
double d2 = 123.456789;
double d3 = 0.0000000123456789;
double d4 = 12345678.9;
double d5 = 4.2;
Console.WriteLine(d0.ToString(6));
Console.WriteLine(d1.ToString(6));
Console.WriteLine(d2.ToString(6));
Console.WriteLine(d3.ToString(6));
Console.WriteLine(d4.ToString(6));
Console.WriteLine(d5.ToString(6));
This is the output:
0.00123
1.23456
123.456
1.23456
123456
4.20000
I don't think this is the best way to solve it, but I like extension methods.
DoubleConverter class: http://1drv.ms/1yEbvL4
If your goal is to avoid "jumping" of the decimal point:
Use g formating, this does the most sensible thing to do
See where the decimal point is in your resulting string
pad with spaces at the beginning to align the column at the decimal point
As I understand, there is no predefined format that does what I need. So for everyone who is interested, here is the function I ended up with:
public string FormatValue(double d, int noOfDigits)
{
double abs = Math.Abs(d);
int left = abs < 1 ? 1 : (int)(Math.Log10(abs) + 1);
int usedDigits = 0;
StringBuilder sb = new StringBuilder();
for(; usedDigits < left; usedDigits++)
{
sb.Append("0");
}
if(usedDigits < noOfDigits)
{
sb.Append(".");
for(; usedDigits < noOfDigits; usedDigits++)
{
sb.Append("0");
}
}
return d.ToString(sb.ToString());
}

String/Int to double with precision defined onruntime

I have an input type integer that represents a number that needs to be converted to double between 1-100, and the rest is decimal precision.
Example: 1562 -> 15.62 ; 198912 -> 19.8912
Right now, I tried a conversion to string, count the number of characters, take 2 to check how many decimals I have and depending of the result "create" a composite string to get a valid double...
Any idea of there is a better way of resolving convert-precision on runtime.
What about this:
int value = 1562;
decimal d = value;
while (d > 100) {
d /= 10;
}
You can use LINQ Skip and Take like:
string str = "198912";
string newStr = string.Format("{0}.{1}", new string(str.Take(2).ToArray()), new string(str.Skip(2).ToArray()));
double d = double.Parse(newStr, CultureInfo.InvariantCulture);
You can add the checks for length on original string, and also use double.TryParse to see if you get valid values.
If you have an int to begin with then you can use decimal, which would provide you more accurate conversion. Like:
int number = 1562123123;
decimal decimalNumber = number;
while (decimalNumber > 100)
{
decimalNumber /= 10;
}
Here is a mathematical solution. The line lg = Math.Max(lg, 0); changes "2" to return "2.0" instead of "20.0" but I guess that depends on your needs for single digit numbers.
static double ToDoubleBetween1And100(int num)
{
var lg = Math.Floor(Math.Log10(num)) - 1;
lg = Math.Max(lg, 0);
return ((double)num) / Math.Pow(10, lg);
}

How to display just first 2 decimals unequal to 0

How can I display the number with just the 2 not=zero decimals?
Example:
For 0.00045578 I want 0.00045 and for 1.0000533535 I want 1.000053
There is no built in formatting for that.
You can get the fraction part of the number and count how many zeroes there are until you get two digits, and put together the format from that. Example:
double number = 1.0000533535;
double i = Math.Floor(number);
double f = number % 1.0;
int cnt = -2;
while (f < 10) {
f *= 10;
cnt++;
}
Console.WriteLine("{0}.{1}{2:00}", i, new String('0', cnt), f);
Output:
1.000053
Note: The given code only works if there actually is a fractional part of the number, and not for negative numbers. You need to add checks for that if you need to support those cases.
My solution would be to convert the number to a string. Search for the ".", then count zeroes till you find a non-zero digit, then take two digits.
It's not an elegant solution, but I think it will give you consistent results.
Try this function, using parsing to find the # of fractional digits rather than looking for zeros (it works for negative #s as well):
private static string GetTwoFractionalDigitString(double input)
{
// Parse exponential-notation string to find exponent (e.g. 1.2E-004)
double absValue = Math.Abs(input);
double fraction = (absValue - Math.Floor(absValue));
string s1 = fraction.ToString("E1");
// parse exponent peice (starting at 6th character)
int exponent = int.Parse(s1.Substring(5)) + 1;
string s = input.ToString("F" + exponent.ToString());
return s;
}
You can use this trick:
int d, whole;
double number = 0.00045578;
string format;
whole = (int)number;
d = 1;
format = "0.0";
while (Math.Floor(number * Math.Pow(10, d)) / Math.Pow(10, d) == whole)
{
d++;
format += "0";
}
format += "0";
Console.WriteLine(number.ToString(format));

Break decimal value into two values (before and after decimal)

How to break a decimal value into integer values, first value should be the value before decimal and the other value of after decimal.
Problem : Decimal place is unknown as well as the number of digits;
ex :
double value = 2635.215;
int firstValue = 2635; // Should be
int secondValue = 215; // Should be
A possible solution:
using System.Globalization;
namespace DecimalSplit
{
class Program
{
static void Main(string[] args)
{
double value = 2635.215;
var values = value.ToString(CultureInfo.InvariantCulture).Split('.');
int firstValue = int.Parse(values[0]);
int secondValue = int.Parse(values[1]);
}
}
}
Using CultureInfo.InvariantCulture when converting to String will ensure that the decimal separator will be a . and the split will be done in the right place. In my culture the decimal separator was a , for example
You can use String.Split method for splitting a string. Convert double to string and then split it based on .
This problem is unsolvable, because a double value can have an extremely large number of decimal digits, so you cannot guarantee to be able to represent them in an integer. The closest I can give you is this, which works not with integers, but with doubles:
double left = System.Math.Floor(value);
double right = left - value;
Here is a little improvment of Răzvan Panda example.
An exception was raised in int secondValue = int.Parse(values[1]); if we parse a value with no decimal.
Another point is that it's better to have a string for the second value. See, example 3.
static void Main(string[] args)
{
double val1 = 2635.215;
Console.Out.WriteLine(GetFirstValue(val1)); // out 2635
Console.Out.WriteLine(GetSecondValue(val1)); // out 215
double val2 = 2;
Console.Out.WriteLine(GetFirstValue(val2)); // out 2
Console.Out.WriteLine(GetSecondValue(val2)); // out ''
double val3 = 3.04;
Console.Out.WriteLine(GetFirstValue(val3)); // out 3
Console.Out.WriteLine(GetSecondValue(val3)); // out 04
}
public static string GetFirstValue(double value)
{
var values = value.ToString(CultureInfo.InvariantCulture).Split('.');
return values[0];
}
public static string GetSecondValue(double value)
{
var values = value.ToString(CultureInfo.InvariantCulture).Split('.');
return values.Length > 1 ? values[1] : string.Empty;
}
try:
double value = 2635.215;
string a = value.ToString();
string[] b =a.Split('.');
int firstValue= int.Parse(b[0]);
int secondValue= int.Parse(b[1]);
You could do:
double decimalNumber = 123.456;
var numbersBeforeDecimalPoint = Math.Truncate(decimalNumber);
var numbersAfterDecimalPoint = decimalNumber - numbersBeforeDecimalPoint;
Using Math.Truncate we can get only the whole numbers, and we can then use that in tandem with our original number to get the decimal part.
This would give you 123 and 0.456 as a result.
Not sure if that's exactly what you're after (I appreciate you might want 123 and 456) - there are lots of good suggestions here for string manipulations to do it if you need more specific formatting.

Categories