How can I add decimal places to a TimeSpan object's totalseconds? - c#

I have a function which returns seconds since epoch:
public static string getEpochSeconds()
{
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
var timestamp = t.TotalSeconds;
return timestamp.ToString();
}
It outputs, for example: 1373689200.79987 but for the purposes of my application, I need it to output one more decimal place digit - for example 1373689200.799873. How is this possible?
Thanks!

Try using
return String.Format("{0}", timestamp.TotalSeconds);
and then you can use the format string. See this MSDN article for formatting information.
Edit 1:
Thanks #MortenMertner for the correct format.
Try using:
return String.Format("{0:N6}", timestamp.TotalSeconds);
to force 6 decimal places.
Edit 2:
You can lookup custom numeric format strings and standard numeric format strings to work out the best way to do this.
One way is to use F instead of N (both of which are standard numeric format strings). N will comma delimit the thousands where F will not.
return String.Format("{0:F6}", timestamp.TotalSeconds);
Edit 3:
As #sa_ddam213 points out in his answer, the standard ToString() method has an overload that accepts a formatting parameter. MSDN documents it here for a Double and you can clearly see that it accepts a standard numeric format string or a custom numeric format string so #sa_daam213's answer works out quite well too and is very similar to your original code but instead of N6 use F6 like in my Edit 2 above.

you can use timestamp.ToString("0.000000")
if you need result without rounding value
return t.TotalSeconds.ToString("F0")+"." +t.ToString("ffffff");

You should be able to add N6 (6 decimal places) to your ToString()
Example:
public static string getEpochSeconds()
{
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
var timestamp = t.TotalSeconds;
return timestamp.ToString("N6");
}

If the last digit is not significant you can use the ToString("N6") (just adds a 0 at the end in this case). But if you want the real last digit, due to some strange way of converting doubles to string by .NET you may need something like the following.
public static string getEpochSeconds()
{
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
//t {15901.03:57:53.6052183} System.TimeSpan
var timestamp1 = t.TotalSeconds;
//timestamp1 1373860673.6052184 double
var tstring1 = timestamp1.ToString("N6");
//tstring1 "1,373,860,673.605220" string
var timestamp = (long)(t.TotalSeconds * 1000000);
//timestamp 1373860673605218 long
string tstring =timestamp.ToString();
//tstring "1373860673605218" string
tstring = tstring.Substring(0, tstring.Length - 6) + "." + tstring.Substring(tstring.Length - 6);
//tstring "1373860673.605218" string
return tstring;
}
I have added the outputs also as a comment. Hope this helps.

Related

How to out-of-range error check this double to string converter with specific decimal precision?

I am using this routine to convert a double to a string with keeping only two decimal numbers:
private string DoubleToString(double num)
{
string buffer = num.ToString();
return buffer.Substring(0, buffer.IndexOf(".") + 2);
}
However, sometimes the actual value of the parameter num is only 1 decimal. How can I error check that?
You should use double's ToString method with a custom format instead https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx
num.ToString("0.00") will guarantee 2 decimals
More about formats -
Standard - https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx
Custom - https://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx

WP8 - C# - Parsing string to decimal FormatException

I am currently trying to parse a string, "277.968", to decimal, but I am getting a FormatException exception.
I have read that I need to perform the decimal parse this way:
string str = "277.968";
decimal.Parse(str, CultureInfo.InvariantCulture);
Still, I am getting the said exception.
What could I do?
EDIT: Fixed float to decimal
Printing the lenght of the string, it reported it being 80 chars long.
Right, well that's the problem then. Your string isn't "277.968" - it's "277.968\0\0\0\0\0\0(...)" - and that can't be parsed.
My guess is that you've read this from a TextReader of some kind, but ignored the return value of Read, which is the number of characters that have been read.
So for example, if your current code is effectively:
char[] risul = new char[80];
reader.Read(risul, 0, risul.Length);
decimal value = decimal.Parse(new string(risul), CultureInfo.InvariantCulture);
then you should instead have:
char[] risul = new char[80];
int charsRead = reader.Read(risul, 0, risul.Length);
decimal value = decimal.Parse(new string(risul, 0, charsRead),
CultureInfo.InvariantCulture);
... although that's still assuming that you're reading all of the appropriate data in a single call to Read, which isn't necessarily the case. You may well just want:
string data = reader.ReadToEnd();
decimal value = decimal.Parse(data, CultureInfo.InvariantCulture);

Remove last characters from a string in C#. An elegant way?

I have a numeric string like this 2223,00. I would like to transform it to 2223. This is: without the information after the ",". Assume that there will be only two decimals after the ",".
I did:
str = str.Remove(str.Length - 3, 3);
Is there a more elegant solution? Maybe using another function? -I donĀ“t like putting explicit numbers-
You can actually just use the Remove overload that takes one parameter:
str = str.Remove(str.Length - 3);
However, if you're trying to avoid hard coding the length, you can use:
str = str.Remove(str.IndexOf(','));
Perhaps this:
str = str.Split(",").First();
This will return to you a string excluding everything after the comma
str = str.Substring(0, str.IndexOf(','));
Of course, this assumes your string actually has a comma with decimals. The above code will fail if it doesn't. You'd want to do more checks:
commaPos = str.IndexOf(',');
if(commaPos != -1)
str = str.Substring(0, commaPos)
I'm assuming you're working with a string to begin with. Ideally, if you're working with a number to begin with, like a float or double, you could just cast it to an int, then do myInt.ToString() like:
myInt = (int)double.Parse(myString)
This parses the double using the current culture (here in the US, we use . for decimal points). However, this again assumes that your input string is can be parsed.
String.Format("{0:0}", 123.4567); // "123"
If your initial value is a decimal into a string, you will need to convert
String.Format("{0:0}", double.Parse("3.5", CultureInfo.InvariantCulture)) //3.5
In this example, I choose Invariant culture but you could use the one you want.
I prefer using the Formatting function because you never know if the decimal may contain 2 or 3 leading number in the future.
Edit: You can also use Truncate to remove all after the , or .
Console.WriteLine(Decimal.Truncate(Convert.ToDecimal("3,5")));
Use:
public static class StringExtensions
{
/// <summary>
/// Cut End. "12".SubstringFromEnd(1) -> "1"
/// </summary>
public static string SubstringFromEnd(this string value, int startindex)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Substring(0, value.Length - startindex);
}
}
I prefer an extension method here for two reasons:
I can chain it with Substring.
Example: f1.Substring(directorypathLength).SubstringFromEnd(1)
Speed.
You could use LastIndexOf and Substring combined to get all characters to the left of the last index of the comma within the sting.
string var = var.Substring(0, var.LastIndexOf(','));
You can use TrimEnd. It's efficient as well and looks clean.
"Name,".TrimEnd(',');
Try the following. It worked for me:
str = str.Split(',').Last();
Since C# 8.0 it has been possible to do this with a range operator.
string textValue = "2223,00";
textValue = textValue[0..^3];
Console.WriteLine(textValue);
This would output the string 2223.
The 0 says that it should start from the zeroth position in the string
The .. says that it should take the range between the operands on either side
The ^ says that it should take the operand relative to the end of the sequence
The 3 says that it should end from the third position in the string
Use lastIndexOf. Like:
string var = var.lastIndexOf(',');

how to format data

I am getting the following values from database:
99, 12, 12.2222, 54.98, 56, 17.556
Now I want to show that values like below:
99%, 12%, 12.22% , 54.98% , 56%, 17.55%
Please give me any suggestion to acchive this.
Its very easy in C#:
[EDIT]
var val = 99.569;
string result = string.Format("{0:0.##}%", val);
You can take a look for Format method of string class:
http://msdn.microsoft.com/en-us/library/fht0f5be.aspx
and I recomend you to take a look on custom format strings:
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
Use the ToString method that takes a string format - the format you want is "P2" or the custom format #0.##%. Both of these formatting options multiply by 100, expecting your data to be in standard percent format so you will need to divide to accomadate and use it.
To use ToString without the divide you can use "#0.##\%" which will format the numeric part and include the percent sign as a literl, this is the equivilent for ToString as the format from Anton Semenov's answer using the string.Format function on this thread.
Msdn article - Standard Formats
Msdn article - Custom Formats
to formart 12.2222 use f
string.Format("{0:f}%", 12.2222); //output 12,22%
Try this Out
List<double> myList = new List<double>();
myList.Add(0.1234);
myList.Add(99);
myList.Add(12.1234);
myList.Add(54.98);
foreach (double d in myList)
{
string First = string.Format("{0:0.00%}", d); //Multiply value by 100
Console.WriteLine(First);
string Second = string.Format("{0:P}", d);//Multiply value by 100
Console.WriteLine(Second);
string Third = string.Format("{0:P}%", d.ToString());//Use this One
Console.WriteLine(Third);
string Four = d.ToString() + "%"; //Not a good idea but works
Console.WriteLine(Four);
Console.WriteLine("=====================");
}
Console.ReadLine();
I have made a little trick here {0:P} will multiply your given value by 100 and then show it but you just want to place a % sign after value so first convert the given value to TOString than apply {0:p}
If you want to specify the number of decimal places to 2 (ie. not 12.2222%, but 12.22%), then use:
val.ToString("0.00") + "%"
Note that this will round the number off, so 12.226 would be shown as 12.23%, etc.

formatting string in C#?

I've a predefined string format. For instance '>>>,>>>,>>9.99' this means that the system should display string in this '500,000,000.10'. The format can change based on the users using it. How can I write a common function to display stings on the given format passing
the input value and the format as the parameter using C#
You can use the ToString method with a standard or custom format string
For example:
string format = "{0:000,000,000.00}";
string val = 12.3456;
Console.WriteLine(string.Format(format, value)); // it prints "000,000,123.23"
You can read more about formating values here http://www.csharp-examples.net/string-format-double/
decimal value = 1.2345;
string rounded = value.ToString("d2");
private string sDecimalFormat = "0.00";
decimal d = 120M;
txtText.Text = d.ToString(sDecimalFormat);
You could then have a setting for decimal format eg:
txtText.Text = d.ToString(Settings.DecimalFormat);
String.formate can be used for formating.
Go there if you want examples
http://www.csharp-examples.net/string-format-double/
I think the following might work:
String result = String.Format(fmt.Replace('>', '#').Replace('9', '0'), inpString);
fmt being the format you want to use and inpString being the string entered by the user.
Just replace the > with # and the 9 with 0 and it'll be a valid .Net formatstring.
There is a Format method on String.
String.Format("{0:X}", 10); // prints A (hex 10)
There are several methods to format numbers, date...
I dont seem to understand how you can make 500,000,000.10 from >>>,>>>,>>9.99' but I believe the answer would be
But I assume something you are looking for is: string.Format("500,000,00{0:0.##}", 9.9915)
You can then make a method like
Public string GetString(string Format, object value)
{
return string.Format(Format, value);
}
Something like this?

Categories