How I can get the value that the user inputs to round to two decimal places. I tried to use.ToString("N2") but it gave me an error of {cannot convert string to System.IFormatProvider}. I can't seem to find a solution to this error.
code is here:
using System;
using System.Text.RegularExpressions;
namespace _selfTest
{
class Program
{
public static void Main(string[] args)
{
const string formula = #"^\d+\.?\d+?\%$";
percentages(formula, Console.ReadLine());
}
public static void percentages(string bottle, string flower)
{
Regex newRegular = new Regex(bottle);
bool input = newRegular.IsMatch(flower);
if (input)
Console.WriteLine("This Percentage Is Correct! " + bottle);
else
Console.WriteLine("This Percentage Is Incorrect... " + bottle);
Console.ReadLine();
}
}
}
You could use Decimal.TryParse method. And then you can use standard numeric format string "N2"
string consoleInput = Console.ReadLine();
if(Decimal.TryParse(consoleInput, out decimal parsedInput))
{
string resultString = parsedInput.ToString("N2");
}
else
{
// handling bad input
}
Your solution is just 2 steps away
Parsing the user input to decimal format
Then rounding off to 2 decimal places
.cs
static void Main(string[] args)
{
//Parse User input
var inputValue = Console.ReadLine();
inputValue = inputValue.Split('%')[0]; //To handle the trailing % sign
decimal outputValue;
var style = NumberStyles.Any;
var culture = CultureInfo.InvariantCulture;
if (Decimal.TryParse(inputValue, style, culture, out outputValue))
Console.WriteLine("Converted '{0}' to {1}.", inputValue, outputValue);
else
Console.WriteLine("Unable to convert '{0}'.", inputValue);
//Rounding off 2 decimal places
var roundedValue = Math.Round(outputValue, 2);
Console.WriteLine(roundedValue);
Console.Read();
}
Note
If you know ahead of time what culture you expect your inputs to be in you can specify that using culture info
var culture = new CultureInfo("en-US");// or ("fr-FR")
I have a string variable that holds the value of "02/04/2018 to 08/04/2018".
string dateRange = "02/04/2018 to 08/04/2018";
I have a function in c# that gets all the date within the range of 02/04/2018 to 08/04/2018 as per below.
public string getDateRange(string dateRange) {
var selectedDates = new List<DateTime?>();
for (var date = Convert.ToDateTime("02/04/2018");
date <= Convert.ToDateTime("08/04/2018");
date = date.AddDays(1)) {
selectedDates.Add(date);
}
foreach (var date in selectedDates) {
Console.WriteLine(date);
}
return selectedDates;
}
What I want to achieve in this method is to remove the word to in the date range and pass the starting date and ending date separately. Can someone please help ?
You can use String.Split() to separate the dates:
public string[] separateDates(string dateRange)
{
string[] dateSplit = dateRange.Split(new string[] { "to" }, StringSplitOptions.RemoveEmptyEntries);
return new string[]{dateSplit[0].Trim(), dateSplit[1].Trim()};
}
The method returns a string array that holds the first ("02/04/2018") and the second date ("08/04/2018"):
static void Main()
{
string dateRange = "02/04/2018 to 08/04/2018";
string[] myDates = separateDates(dateRange);
string firstDate = myDates[0];//"02/04/2018"
string secondDate = myDates[1];//"08/04/2018"
}
EDIT:
I have implemented my method that separates the dates into your method:
public List<DateTime?> getDateRange(string dateRange)
{
var selectedDates = new List<DateTime?>();
string[] dateSplit = dateRange.Split(new string[] { "to" }, StringSplitOptions.RemoveEmptyEntries);
for (var date = Convert.ToDateTime(dateSplit[0].Trim());
date <= Convert.ToDateTime(dateSplit[1].Trim());
date = date.AddDays(1))
{
selectedDates.Add(date);
}
foreach (var date in selectedDates)
{
Console.WriteLine(date.Value.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
}
return selectedDates;
}
The method now returns List<DateTime?> instead of string because the type of selectedDates is List<DateTime?>. I also made a modification to the console output, now the dates are printing to the console in the following format dd/MM/yyyy (e.g. 02/04/2018).
LastIndexOf: This method searches strings from the right. It finds the location of the last occurrence of a letter or substring. It is the reversed version of IndexOf.
public static void Main(string[] args)
{
string str = "02/04/2018 to 08/04/2018";
int pos = str.LastIndexOf("to");
string result = str.Substring(0, pos) + " " + str.Substring(pos + 2);
Console.WriteLine(result);
}
Fiddle
Its printing the date as : 02.04.2018 00:00:00. I have specified the string to dd/MM/yyyy. It just removes the 00:00:00 but keeps the dot in between.
Here is the little amendment to fix that:
Console.WriteLine(date.Value.ToString("dd/MM/yyyy"));
I work on a project in C# which requires to use arabic numbers, but then it must store as integer in database, I need a solution to convert arabic numbers into int in C#.
Any solution or help please?
thanks in advance
From comments:
I have arabic numbers like ١،٢،٣،٤... and must convert to 1,2,3, or ٢٣٤ convert to 234
Updated: You can use StringBuilder for memory optimization.
private static string ToEnglishNumbers(string input)
{
StringBuilder sbEnglishNumbers = new StringBuilder(string.Empty);
for (int i = 0; i < input.Length; i++)
{
if (char.IsDigit(input[i]))
{
sbEnglishNumbers.Append(char.GetNumericValue(input, i));
}
else
{
sbEnglishNumbers.Append(input[i].ToString());
}
}
return sbEnglishNumbers.ToString();
}
Original Answer: use this Method
private string toEnglishNumber(string input)
{
string EnglishNumbers = "";
for (int i = 0; i < input.Length; i++)
{
if (Char.IsDigit(input[i]))
{
EnglishNumbers += char.GetNumericValue(input, i);
}
else
{
EnglishNumbers += input[i].ToString();
}
}
return EnglishNumbers;
}
Unfortunately it is not yet possible to parse the complete string representation by passing in an appropriate IFormatProvider(maybe in the upcoming versions). However, the char type has a GetNumericValue method which converts any numeric Unicode character to a double. For example:
double two = char.GetNumericValue('٢');
Console.WriteLine(two); // prints 2
You could use it to convert one digit at a time.
Arabic digits like ١،٢،٣،٤ in unicode are encoded as characters in the range 1632 to 1641. Subtract the unicode for arabic zero (1632) from the unicode value of each arabic digit character to get their digital values. Multiply each digital value with its place value and sum the results to get the integer.
Alternatively use Regex.Replace to convert the string with Arabic digits into a string with decimal digits, then use Int.Parse to convert the result into an integer.
A simple way to convert Arabic numbers into integer
string EnglishNumbers="";
for (int i = 0; i < arabicnumbers.Length; i++)
{
EnglishNumbers += char.GetNumericValue(arabicnumbers, i);
}
int convertednumber=Convert.ToInt32(EnglishNumbers);
This is my solution :
public static string arabicNumToEnglish(string input)
{
String[] map={"٠","١","٢","٣","٤","٥","٦","٧","٨","٩"};
for (int i = 0; i <= 9; i++)
{
input=input.Replace(map[i],i.ToString());
}
return input;
}
to get the value of a digit, substract the zero character from it, e.g in normal numeric, '1'-'0' = 1, '2'-'0' = 2. etc.
For multidigit number you can use something like this
result =0;
foreach(char digit in number)
{
result *= 10; //shift the digit, multiply by ten for each shift
result += (digit - '0)'; //add the int value of the current digit.
}
just replace the '0' with the arabic zero if your number uses Arabic character. This works for any numeric symbols, as long as 0-9 in that symbol system are encoded consecutively.
I know this question is a bit old, however I faced similar case in one of my projects and passed by this question and decided to share my solution which did work perfectly for me, and hope it will serve others the same.
private string ConvertToWesternArbicNumerals(string input)
{
var result = new StringBuilder(input.Length);
foreach (char c in input.ToCharArray())
{
//Check if the characters is recognized as UNICODE numeric value if yes
if (char.IsNumber(c))
{
// using char.GetNumericValue() convert numeric Unicode to a double-precision
// floating point number (returns the numeric value of the passed char)
// apend to final string holder
result.Append(char.GetNumericValue(c));
}
else
{
// apend non numeric chars to recreate the orignal string with the converted numbers
result.Append(c);
}
}
return result.ToString();
}
now you can simply call the function to return the western Arabic numerals.
try this extension:
public static class Extension
{
public static string ToEnglishNumbers(this string s)
{
return s.Replace("۰", "0").Replace("۱", "1").Replace("۲", "2").Replace("۳", "3").Replace("۴", "4")
.Replace("۵", "5").Replace("۶", "6").Replace("۷", "7").Replace("۸", "8").Replace("۹", "9");
}
public static int ToNumber(this string s)
{
if (int.TryParse(s.ToEnglishNumbers(), out var result))
{
return result;
}
return -1;
}
public static string ToArabicNumbers(this string s)
{
return s.Replace("0", "۰").Replace("1", "۱").Replace("2", "۲").Replace("3", "۳").Replace("4", "۴")
.Replace("5", "۵").Replace("6", "۶").Replace("7", "۷").Replace("8", "۸").Replace("9", "۹");
}
}
I have an array that stores date input from users but I want to remove or trim the first two characters (basically, I want to remove the month) from every date inputted in the array:
class MainClass
{
{
//Main Program....
}
public static int GetInput (string[] date)
{
int loop;
(for int i=0 ; i < loop ; i++)
dArray[i] = Console.ReadLine();
}
}
class OtherClass
{
//Required data properties, etc...
public string TrimFirstTwoMonthChar(string dateInput)
{
char[] delimiter = {'/', '-', .... }
string[] monthNumberRemoved = dateInput.Split(delimeter);
// How would I code the rest of this function so that it removes the first 2 characters from "MM/dd/yyyy".
//Keep in mind I have also allowed users to input the date in formats like
//"M/dd/yyyy" (such as 3/07/2011 vs 03/07/2011)
//so sometimes I would only need to remove ONE NOT TWO of the month character //
}
}
With string, you can use a simple substring:
public static string TrimFirstTwoMonthChar(string dateInput)
{
var indexOfFirstBar = dateInput.IndexOf('/');
var start = indexOfFirstBar + 1;
return dateInput.Substring(start, dateInput.Length - start);
}
But I suggest you to convert to DateTime and use the date format you want:
public static string TrimFirstTwoMonthChar(string dateInput)
{
var date = Convert.ToDateTime(dateInput);
return date.ToString("dd/yyyy"); // Use the format you want here
}
About Convert.ToDateTime and date formats.
Something like this?
public string TrimFirstTwoMonthChar(string dateInput)
{
char[] delimiter = {'/', '-', .... }
string[] monthNumberRemoved = dateInput.Split(delimeter);
return monthNumberRemoved[1] + "/" + monthNumberRemoved[2];
}
I have a string which typically is in the format : "0xFF".
I'll trim it since there is a chance of whitespace.
How do i convert that into hex and convert "34" to decimal?
I know about .Parse but does this support hex characters when the string is "0x123"?
You'll have to strip the "0x" part, but this snippet works:
using System;
using System.Globalization;
public class StrToInt {
public static void Main(string[] args) {
string val = "FF";
int num = Int32.Parse(val, NumberStyles.AllowHexSpecifier);
Console.WriteLine(num);
}
}
int i = int.Parse( "FF", System.Globalization.NumberStyles.HexNumber );
MessageBox.Show( i.ToString() ); // displays 255
However, you will need to trim the leading "0x".