formatting decimals using string format - c#

public static string PadZero(this double number, int decimalPlaces)
{
var requiredFormat = "0." + "".PadRight(decimalPlaces, '0');
var something = $"{number:requiredFormat}";
return number.IsNotZero() ? something: string.Empty;
}
This is a helper function to pad zeros to a double number, user can pass the number of zeros that is required to be padded through decimalPlaces.
Above function fails my unit tests, output received is {requiredFormat} in all test cases.
I have just replaced: var something = $"{number:0.00}"; with a generic variable requiredFormat that can handle any number of zero padding.

There are two problems with your example. The first is that the value of something is not going to produce a string that can be used to format a number. The second is that you are not using something to perform a number format by using string.format.
So first off, the statement:
var something = $"{number:requiredFormat}";
is not going to give you the result that you want, which would be a string that looks something like:
{0:0.0000}
Try changing the code to read:
var something = $"{{0:{requiredFormat}}}";
If you do Console.WriteLine(something) after that statement executes you can inspect the value of something to make sure it is what you are looking for.
After that, change this line:
return number.IsNotZero() ? something: string.Empty;
to read:
return number.IsNotZero() ? string.Format(something, number) : string.Empty;
Even with Interpolated Strings, you have to build the variable format and apply it in two separate steps.
Hope that helps.

Related

Get only numbers from line in file

So I have this file with a number that I want to use.
This line is as follows:
TimeAcquired=1433293042
I only want to use the number part, but not the part that explains what it is.
So the output is:
1433293042
I just need the numbers.
Is there any way to do this?
Follow these steps:
read the complete line
split the line at the = character using string.Split()
extract second field of the string array
convert string to integer using int.Parse() or int.TryParse()
There is a very simple way to do this and that is to call Split() on the string and take the last part. Like so if you want to keep it as a string:
var myValue = theLineString.Split('=').Last();
If you need this as an integer:
int myValue = 0;
var numberPart = theLineString.Split('=').Last();
int.TryParse(numberPart, out myValue);
string setting=sr.ReadLine();
int start = setting.IndexOf('=');
setting = setting.Substring(start + 1, setting.Length - start);
A good approach to Extract Numbers Only anywhere they are found would be to:
var MyNumbers = "TimeAcquired=1433293042".Where(x=> char.IsDigit(x)).ToArray();
var NumberString = new String(MyNumbers);
This is good when the FORMAT of the string is not known. For instance you do not know how numbers have been separated from the letters.
you can do it using split() function as given below
string theLineString="your string";
string[] collection=theLineString.Split('=');
so your string gets divided in two parts,
i.e.
1) the part before "="
2) the part after "=".
so thus you can access the part by their index.
if you want to access numeric one then simply do this
string answer=collection[1];
try
string t = "TimeAcquired=1433293042";
t= t.replace("TimeAcquired=",String.empty);
After just parse.
int mrt= int.parse(t);

How do I trim the "0." after I do modulo 1 on a double variable

Hello everyone as the title say I want to trim the "0." after I do modulo 1 on a double variable
Example:
double Number;
Number = Convert.ToDouble(Console.ReadLine()); //12.777
test = Number % 1; //0.777
I want my output to be: 777
only using math with no
string trims and so...
Thank you all !!
and in c# please
That is just a formatting on the ToString. Take a look at all your options here
How about
.ToString(".###");
Without using any string functions!
while(Math.Round(Number-(int)Number,1)!=1)
{
Number=Number/0.1;
if(Number-(int)Number==0)break;//To cover edge case like 0.1 or 0.9
}
NOTE: Number should be of double type!
If I take your question literally, then you do not want the decimal point either, so .ToString(".###") will not get you what you want, unless you remove the first character (which is string manipulation, and you said you don't want that either).
If you want 777 in a numeric variable (not a string), then you can multiply your result by 1000, though I don't know if you'll always have exactly 3 digits after the decimal or not.
The easiest way really is just to use string manipulation. ToString the result without any formatting, then get the substring starting after the decimal. For example:
var x = (.777d).ToString();
var result = x.SubString(x.IndexOf('.') + 1);
You are certainly looking for this:-
.ToString(".###");
As correctly pointed by Marc in comments you should have everything to be in a string, because if you output that 0.777 as it really is stored internally, you'd get 8 random bytes.
Something like this:-
var num = (.777d).ToString();
var result = num.SubString(num.IndexOf('.') + 1);
The most generic way to do this would be:
using System.Globalization;
var provider = NumberFormatInfo.InvariantInfo;
var output = test.ToString(".###", provider)
.Replace(provider.NumberDecimalSeparator, String.Empty);
You can also set the NumberDecimalSeparator on a custom NumberFormatInfo, but if you set it to empty it will throw the exception "Decimal separator cannot be the empty string."

Easy way to check FormatString is valid?

Is there an easy way to check if a format string is valid? For example the following is code that we use to test a number format string;
public static bool IsValidFormatStringNumber(string FormatString)
{
try
{
const decimal number = 0.056m;
var formattedNumber = number.ToString(FormatString);
return formattedNumber.Length > 0;
}
catch
{
return false;
}
}
We're trying to catch an exception or determine if the resulting string has no length. This test fails however as a format string of "hsibbur" (Any rubbish) results in a string of "hsaibbur", which has length.
We want to do the same test for Percent and Date format string.
If you just want to check for standard format strings, just check that your format strings are part of that list.
If you want to check for custom format strings (that are not "Other" or "Literal strings"), you can probably craft a regex to do it.
Other than that, since format strings can be arbitrary strings, I don't think validation even applies.
If FormatString is equal to formattedNumber, that could be another case for returning false.

Get characters behind the dot in of a double

I feel like this is a very noob question.. but I just can't get the right statement for it.
For display purposes, I want to split a double in two: the part before the dot and the first two digits after the dot. I need it as a string. Target language: C#.
E.g.: 2345.1234 becomes "2345" and "12"
I know how to get the part before the dot, that's simply:
Math.Floor(value).ToString()
...but what is the right way to get the part "behind the dot"?
There must be some nice way to do that in a simple way...
I can't think of anything else then:
Math.Round(100 * (value - Math.Floor(value))).ToString("00");
I'm sure there is a better way, but I just can't think of it. Anyone?
Regular expressions (regex) is probably you best bet, but using the mod operator may be another valuable solution...
stuffToTheRight = value % 1
Cheers.
//
//Use the Fixed point formatting option. You might have a bit more work to do
//if you need to handle cases where "dot" is not the decimal separator.
//
string s = value.ToString("F2", CultureInfo.InvariantCulture);
var values = s.Split(".");
string v1 = values[0];
string v2 = values[1];
See this link for more about formatting: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
Here is some untested code that tries to take current culture into account:
//
//Use the Fixed point formatting option.
//
string s = value.ToString("F2", CultureInfo.CurrentCulture);
var values = s.Split(CultureInfo.NumberFormat.NumberDecimalSeparator);
string v1 = values[0];
string v2 = values[1];
use regex ".[0-9][0-9]"
In one line it will be:
string[] vals = value.ToString("f2").Split(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator.ToCharArray());
vals[0] : before point.
vals[1] : after point.

How to Parse a String to Double

Here is my string
20.0e-6
I'm parsing it like
String Ans=Double.Parse("20.0e-6")
Now i'm getting the result like 2E-05
But the required output should be like
0.00002
How to get this?
The result of Double.Parse is a Double, not a string. You need to output a string from the double, using ToString.
You should also use an overload of Double.Parse that has a NumberStyles parameter. Using the Float value allows exponent notation:
string Ans=Double.Parse("20.0e-6", NumberStyles.Float).ToString("0.#####");
If you don't want to risk exceptions (InvlidCastException for example), you can use TryParse:
Double res;
if (Double.TryParse("20.0e-6", NumberStyles.Float,
CultureInfo.InvariantCulture ,res))
{
string Ans = res.ToString("0.#####");
}
It's the same number, but if you want to modify the output of the string, use a formatter on your ToString()
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
So
String Ans=Double.Parse("20.0e-6").ToString("0.0####")
One way to get the result you want is to use String.Format as follow:
double x = 20.0e-6;
string y = string.Format("{0:0.######}",x);
Console.WriteLine(y);
Given your example, this outputs the value 0.00002
EDIT
I've just realised that this is actually the opposite of your question so in the aim of keeping the answer useful i'll add the following:
Given a string, you can parse as double and then apply the same logic as above. Probably not the most elegant solution however it offers another way to get the result you want.
string x = "20.0e-6";
var y = double.Parse(p);
Console.WriteLine(String.Format("{0:0.######}",y));

Categories

Resources