Convert string start with 0 to 2 decimal place asp.net? - asp.net

I have this string:
Dim value as String = "0.11209176170341301"
And tried to use this code to convert the string into decimal with two places:
Dim value as String = "0.11209176170341301"
Dim valueInDecimal As Decimal
If [Decimal].TryParse(value, valueInDecimal) Then
Console.WriteLine(valueInDecimal.ToString("0:0.#"))
End If
I get this result:
11209176170341301D
I need to get this:
0.11
What I'm doing wrong?
I want to get as result a decimal with two placesfrom the string value

You can use basic string operations also:
string value = "0.11209176170341301";
var parts = value.Split('.');
var floatingPart = parts[1].Substring(0, 2);
var truncatedValue = parts[0] + "," + floatingPart;
decimal d = decimal.Parse(truncatedValue);
string s = d.ToString();
Console.Write(s);
Console.Read();
If you are only needed it as string then you can just truncate it as string then it will be easier like:
string value = "0.11209176170341301";
var parts = value.Split('.');
var floatingPart = parts[1].Substring(0, 2);
var truncatedValue = parts[0] + "," + floatingPart;
Console.Write(truncatedValue);
Or even you do not convert '.' to ',' then it will be like this:
string value = "0.11209176170341301";
var parts = value.Split('.');
var floatingPart = parts[1].Substring(0, 2);
var truncatedValue = string.Join(".",parts[0],floatingPart);
Console.Write(truncatedValue);

Use Math.Round function
var x = "0.11209176170341301";
Console.Write(Math.Round(Convert.ToDecimal(x), 2));

Related

how to make double from string

My user never value to a pop up and I add .0 at the end however once I convert the value to double the value is edited to only 2 and I need the value 2.0
if (pResult.Ok && !string.IsNullOrWhiteSpace(pResult.Text))
{
var test = pResult.Text + ".0";
double doub = Convert.ToDouble(test);
_settingsService.TimeOutIdentification = doub;
}
Please use following code to convert it
string str1 = String.Format("{0:F}", test);

separating decimal numbers with commas in asp.net eg:1,23,456

I tried this format, got output as 1,234,567,890.00
but I need in this format
1,23,567
decimal unitPrice = 1234567890.00m;
TextBox1.Text = Convert.ToDecimal(unitPrice).ToString("##,#0.00");
I guess you can do this by creating a custom number format info for your needs...example is here for your reference -
int yourNumber = 111234;
NumberFormatInfo nfo = new NumberFormatInfo();
nfo.CurrencyGroupSeparator = ",";
nfo.NumberGroupSizes = new int[] { 3, 2 };
string str = yourNumber.ToString("N0", nfo);
Response.Write("answer is : " + str);

How to get a variable replaced with a field name in a LINQ?

string companyName="ABC";
var query = from q in context.Company where q.CompanyName == companyName select q;
Is there any way to replace the q.CompanyName part of the query with a string variable
so that the field used for filtering be a parametric?
I tried
string str1 = "companySize";
string str2 = "q." + str1;
string companySize = "Mid";
var query = from q in context.Company where str2 == companySize select q;
Didn't work.
Been trying to let the user choose the columns for the query.
Read more about both below option at : Dynamic query with Linq
you can use one of this
Use Dynamic LINQ library
Example for the the blog below
string strWhere = string.Empty;
string strOrderBy = string.Empty;
if (!string.IsNullOrEmpty(txtAddress.Text))
strWhere = "Address.StartsWith(\"" + txtAddress.Text + "\")";
if (!string.IsNullOrEmpty(txtEmpId.Text))
{
if(!string.IsNullOrEmpty(strWhere ))
strWhere = " And ";
strWhere = "Id = " + txtEmpId.Text;
}
if (!string.IsNullOrEmpty(txtDesc.Text))
{
if (!string.IsNullOrEmpty(strWhere))
strWhere = " And ";
strWhere = "Desc.StartsWith(\"" + txtDesc.Text + "\")";
}
if (!string.IsNullOrEmpty(txtName.Text))
{
if (!string.IsNullOrEmpty(strWhere))
strWhere = " And ";
strWhere = "Name.StartsWith(\"" + txtName.Text + "\")";
}
EmployeeDataContext edb = new EmployeeDataContext();
var emp = edb.Employees.Where(strWhere);
Predicate Builder
EXample
var predicate = PredicateBuilder.True<employee>();
if(!string.IsNullOrEmpty(txtAddress.Text))
predicate = predicate.And(e1 => e1.Address.Contains(txtAddress.Text));
if (!string.IsNullOrEmpty(txtEmpId.Text))
predicate = predicate.And(e1 => e1.Id == Convert.ToInt32(txtEmpId.Text));
if (!string.IsNullOrEmpty(txtDesc.Text))
predicate = predicate.And(e1 => e1.Desc.Contains(txtDesc.Text));
if (!string.IsNullOrEmpty(txtName.Text))
predicate = predicate.And(e1 => e1.Name.Contains(txtName.Text));
EmployeeDataContext edb= new EmployeeDataContext();
var emp = edb.Employees.Where(predicate);
If you don't want to use libraries like dynamicLINQ, you can just create the Expression Tree by yourself:
string str1 = "companySize";
string str2 = "q." + str1;
string companySize = "Mid";
var param = Expression.Parameter(typeof(string));
var exp = Expression.Lambda<Func<Company, bool>>(
Expression.Equal(
Expression.Property(param, str1),
Expression.Constant(companySize)),
param);
var query = context.Company.Where(exp);
I think the best way to do this is with built in libraries (and PropertyDescriptor type).
using System.ComponentModel;
void Main()
{
Test test = new Test();
test.CompanyName = "ABC";
object z = TypeDescriptor.GetProperties(test).OfType<PropertyDescriptor>()
.Where(x => x.Name == "CompanyName").Select(x => x.GetValue(test)).FirstOrDefault();
Console.WriteLine(z.ToString());
}
public class Test
{
public string CompanyName { get; set; }
}

DateTime Not working in Global.asax in c#

I am trying to use DateTime in global.asax to give a name to a file but it gives an error. Could you please assist?
The code I am using for the DateTime;
public void callFileCreate()
{
string path = ConfigurationManager.AppSettings["LogFileFolder"].ToString();
string filename = HttpContext.Current.Server.MapPath(path + "\\Log_" + DateTime.Now.ToShortDateString().Replace("/", ".") + "_" + (DateTime.Now.ToLongTimeString()).Replace(":", "_") + ".txt");
TraceFilePath = HttpContext.Current.Server.MapPath(path + "\\Scheduler" + DateTime.Now.ToShortDateString().Replace("/", ".") + "_" + (DateTime.Now.ToLongTimeString()).Replace(":", "_") + ".txt");
FileStream fs = null, fs1 = null;
fs = File.Create(filename);
fs1 = File.Create(TraceFilePath);
ErrorFilePath = filename;
}
You should use the Path class if you work with paths:
string path = ConfigurationManager.AppSettings["LogFileFolder"].ToString();
string fileName = string.Format("{0}_{1}_{2}.txt"
, "Log"
, DateTime.Today.ToString("dd.MM.yyyy") // change according to your actual culture
, DateTime.Now.ToString("HH_mm_ss"));
string fullPath = Path.Combine(path, fileName);
Not sure if that solves your issue, but it increases readability and avoids careless mistakes anyway.
You don't write what error you get. But here are some hints about how you can simplify your code:
var dir = HttpContext.Current.Server.MapPath(
ConfigurationManager.AppSettings["LogFileFolder"].ToString());
var dt = DateTime.Now.ToString("yyyy.MM.dd_HH.mm.ss");
var logFilePath = Path.Combine(dir, string.Format("Log_{0}.txt", dt));
var traceFilePath = Path.Combine(dir, string.Format("Scheduler_{0}.txt", dt));
var fs = File.Create(logFilePath);
var fs1 = File.Create(traceFilePath);
Notes:
if the app-settings entry LogFileFolder already contains an (absolute) filesystem-path such as c:\temp, then you shouldn't call Server.MapPath().
you should call fs.Close() once you no longer need the streams (or put it in a using block). Otherwise, another attempt to create the (same) file will result in an exception.

Getting date as string - need to convert

Programming in Flex 4.5
I'm getting a date as a String.
I don't know what date or hour I'm getting.
I want to convert the string to date and take only the hours & minutes.
For example:
Getting - "2012-02-07T13:35:46+02:00"
I want to see: 13:35.
Suggestions or any other solutions?
After some digging, Solution:
var myDate:Date;
myDate = DateFormmater.parseDateString(myDateString);
var dateResult:String = myDate.getHours() + ":" + myDate.getMinutes();
Thanks anyway! :-)!
You can to use date.getHours() and date.getMinutes(). Try the following:
var d:Date = DateField.stringToDate("your_date_string","YYYY-MM-DD");
trace("hours: ", date.getHours()); // returns 13
trace("minutes: ", date.getMinutes()); // returns 35
private function init():void
{
var isoStr:String = "2012-02-07T13:35:46+02:00";
var d:Date = new Date;
d = isoToDate(isoStr)
trace(d.hours);
}
private function isoToDate(value:String):Date
{
var dateStr:String = value;
dateStr = dateStr.replace(/\-/g, "/");
dateStr = dateStr.replace("T", " ");
dateStr = dateStr.replace("+02:00", " GMT-0000");
return new Date(Date.parse(dateStr));
}
I see you've already got the answer, but for future users, here it is.
var myDateString:String="2012-02-07T13:35:46+02:00"
//This is of the format <yyyy-mm-dd>T<hh:mm:ss><UTC-OFFSET AS hh:mm>
//You could write your own function to parse it, or use Flex's DateFormatter class
var myDate:Date=DateFormatter.parseDateString(myDateString);
//Now, myDate has the date as a Flex Date type.
//You can use the various date functions. In this case,
trace(myDate.getHours()); //Traces the hh value
trace(myDate.getMinutes()); //Traces the mm value

Resources