c# - Convert number in string to have certain number of digits - c#

I have a number in string format. This number will be between 1-6 digits and i need to convert it to be filled with zeroes on left side in order to always be 6 digit number. Is there any more efficient way than this?
Int32.Parse("5").ToString("D6")
Conversion to int just feels a bit unnecessary.

You could use String.PadLeft:
string result = number.PadLeft(6, '0');
If the number can be negative this doesn't work and you need your int.Parse approach.

It is unnecessary
string result = "5".PadLeft(6,'0');

string someText = "test 5 rate";
someText = Regex.Replace(someText, #"\d+", n => n.Value.PadLeft(5, '0'));

Related

ToString format for fixed length of output - mixture of decimal and integer

I'm writing some code to display a number for a report. The number can range from 1. something to thousands, so the amount of precision I need to display depends on the value.
I would like to be able to pass something in .ToString() which will give me at least 3 digits - a mixture of the integer part and the decimal part.
Ex:
1.2345 -> "1.23"
21.552 -> "21.5"
19232.12 -> "19232"
Using 000 as a format doesn't work, since it doesn't show any decimals, neither does 0.000 - which shows too many decimals when the whole part is larger than 10.
You could write an extension method for this:
public static string ToCustomString(this double d, int minDigits = 3)
{
// Get the number of digits of the integer part of the number.
int intDigits = (int)Math.Floor(Math.Log10(d) + 1);
// Calculate the decimal places to be used.
int decimalPlaces = Math.Max(0, minDigits - intDigits);
return d.ToString($"0.{new string('0', decimalPlaces)}");
}
Usage:
Console.WriteLine(1.2345.ToCustomString()); // 1.23
Console.WriteLine(21.552.ToCustomString()); // 21.6
Console.WriteLine(19232.12.ToCustomString()); // 19232
Console.WriteLine(1.2345.ToCustomString(minDigits:4)); // 1.235
Try it online.
I don't think this can be done with ToString() alone.
Instead, start by formatting the number with 2 trailing digits, then truncate as necessary:
static string FormatNumber3Digits(double n)
{
// format number with two trailing decimals
var numberString = n.ToString("0.00");
if(numberString.Length > 5)
// if resulting string is longer than 5 chars it means we have 3 or more digits occur before the decimal separator
numberString = numberString.Remove(numberString.Length - 3);
else if(numberString.Length == 5)
// if it's exactly 5 we just need to cut off the last digit to get NN.N
numberString = numberString.Remove(numberString.Length - 1);
return numberString;
}
Here's a regex, that will give you three digits of any number (if there's no decimal point, then all digits are matched):
#"^(?:\d\.\d{1,2}|\d{2}\.\d|[^.]+)"
Explanation:
^ match from start of string
either
\d\.\d{1,2} a digit followed by a dot followed by 1 or 2 digits
or
\d{2}\.\d 2 digits followed by a dot and 1 digit
or
[^.]+ any number of digits not up to a dot.
First divide your number and then call ToString() before the regex.
Simple way to implement this just write
ToString("f2") for two decimal number just change this fnumber to get your required number of decimal values with integer values also.

C# Reducing numbers in scientific notation from E+### to E+##

Using .ToString("E4") prints a number like 1.2345E+012.
How can I make it print one less number in the exponential part. In other words, print 1.2345E+12.
Thanks!
You can use a custom format string with the E indicator, which takes the minimum number of digits:
double value = 1234567890000;
Console.WriteLine(value.ToString("0.####E+0"));
// 1.2346E+12
You could always store '.ToString("E4")' in a string called "output". Then print "output" character by character until you read a "+" character in "output". Don't print the next character if it's a "0", keep checking for "0"s until you reach something that does not equal (!=) a "0" character and then print the last characters.
Try that code:
var number = 1234567890000;
var exponential = number.ToString("E4");
var splitted = exponential.Split('+');
var result = splitted.Length == 2 ? $"{splitted[0]}+{Convert.ToInt32(splitted[1])}" : exponential;
It takes the number, evaluates the exponential string and removes all leading zeros.
This is done by splitting at the + (if there is one, otherwise it's not neccessary and there won't be any leading zeros) and converting the string, of which the zero shall get removed, to a number. As numbers aren't stored with leading zeros, converting it back to a string removes the leading zeros.
If you want to prevent cases where E+0 is written at the end, check the converted string for 0 and if so use the first part of the splitted string without the last character.

Replace user defined string between a decimal number in c# using regex

I have a string with decimal numbers. For some other reason, I want to replace a character instead of "." between the decimal number.
For example,
string str="SAIF Partners had invested $22.5 million in 2006."
What I need is, I want to replace a character between the $22.5 like this $22r!5.
So my final string would be like this,
string final="SAIF Partners had invested $22r!5 million in 2006."
how can I achieve this? Any help would be really appreciated.
I tried the below code. But I think I am missing something.
string final= Regex.Replace(str, #"[^\D]+", "r!");
string input = "SAIF Partners had invested $22.5 million in 2006.";
var output = Regex.Replace(input, #"(\d+)(\.)(\d+)", "$1r!$3");
(?<=\d)\.(?=\d)
Use lookarounds.See demo.Replace by r! or whatever characters you want to put
https://regex101.com/r/sS2dM8/12
var output = Regex.Replace(input, #"(?<=\d)\.(?=\d)", "r!");

Take only numbers from string and put in an array

ok i found this for removing all 'junk' that is not a number from a string
TextIN = " 0 . 1 ,2 ; 3 4 -5 6 ,7 ,8; 9 "
string justNumbers = new String(textIN.Where(Char.IsDigit).ToArray());
= "0123456789"
this removes all "junk" from my string leaving me just the numbers, but still how i can modify this ,
so i can have at least one delimiter for example a ' , ' b etween my numbers like "0,1,2,3,4,5,6,7,8,9" because i need to delimit this number so i can put them in an array of ints and work with them and there are not always just one digit numbers i may have 105 , 85692 etc..
any help please ?!
You can also convert to numeric values like this:
int[] numbers = Regex.Matches(textIN, "(-?[0-9]+)").OfType<Match>().Select(m => int.Parse(m.Value)).ToArray();
#L.B: agreed, but nthere might be negative values, too.
string test = string.Join(",", textIN.Where(Char.IsDigit));
For n digit numbers you can use regex.
string s = String.Join(",",
Regex.Matches(textIN,#"\d+").Cast<Match>().Select(m=>m.Value));
string justNumbers = new String(textIN.Where(Char.IsDigit).ToArray()); = "0123456789"
string[] words = justNumbers.Split(',');
will seperate the string into an array of numbers, delimited by commas.

combine string.format arguments

I want to generate a 4 character hex number.
To generate a hex number you can use
string.format("{0:X}", number)
and to generate a 4 char string you can use
string.format("{0:0000}", number)
Is there any way to combine them?
I'm assuming you mean: 4-digit hexadecimal number.
If so, then yes:
string.Format("{0:X4}", number)
should do the trick.
Have you tried:
string hex = string.Format("{0:X4}", number);
? Alternatively, if you don't need it to be part of a composite pattern, it's simpler to write:
string hex = number.ToString("X4");

Categories