Truncate decimals beyond first positive - c#

C# - truncate decimals beyond first positive
a number is 0.009012
result should be 0.009
or is 1.1234 and 'd be 1.1
or 2.099 ~ 2.09
and so on
in a fast and optimum way

Think mathematically, use logarithmus with base 10
this function will just take the first cipher
public double RoundOnFirstDecimal(double number)
{
int shift = -1 * ((int)Math.Floor(Math.Log10(number)));
return Math.Floor(number * Math.Pow(10, shift)) / Math.Pow(10, shift);
}
But you want to have it this way: (will shift only regarding the decimal fractions, but not full numbers)
public double RoundOnFirstDecimal(double number)
{
int shift = -1 * ((int)Math.Floor(Math.Log10(number % 1)));
return Math.Floor(number % 1 * Math.Pow(10, shift)) / Math.Pow(10, shift) + number - number % 1;
}
thats gonna be significantly faster than any regex or looping

Try this method:
private static string RoundSpecial(double x)
{
string s = x.ToString();
int dotPos = s.IndexOf('.');
if (dotPos != -1)
{
int notZeroPos = s.IndexOfAny(new[] { '1', '2', '3', '4', '5', '6', '7', '8', '9' }, dotPos + 1);
return notZeroPos == -1 ? s : s.Substring(0, notZeroPos + 1);
}
return s;
}
I'm not sure that it is the fastest and optimal method, but it does what you want.
Second approach is to use Log10 and %:
private static double RoundSpecial(double x)
{
int pos = -(int)Math.Log10(x - (int)x);
return Math.Round(x - (x % Math.Pow(0.1, pos + 1)), pos + 1);
}

You may try regular expression too:
decimal d = 2.0012m;
Regex pattern = new Regex(#"^(?<num>(0*[1-9]))\d*$");
Match match = pattern.Match(d.ToString().Split('.')[1]);
string afterDecimal = match.Groups["num"].Value; //afterDecimal = 001

Here's a solution that uses math instead of string logic:
double nr = 0.009012;
var partAfterDecimal = nr - (int) nr;
var partBeforeDecimal = (int) nr;
int count = 1;
partAfterDecimal*=10;
int number = (int)(partAfterDecimal);
while(number == 0)
{
partAfterDecimal *= 10;
number = (int)(partAfterDecimal);
count++;
}
double dNumber = number;
while(count > 0){
dNumber /= 10.0;
count--;
}
double result = (double)partBeforeDecimal + dNumber;
result.Dump();

if you don't want to use the Math library:
static double truncateMyWay(double x)
{
double afterDecimalPoint = x - (int)x;
if (afterDecimalPoint == 0.0) return x;
else
{
int i = 0;
int count10 = 1;
do
{
afterDecimalPoint *= 10;
count10 *= 10;
i++;
} while ((int) afterDecimalPoint == 0);
return ((int)(x * count10))/((double)count10);
}
}
Happy Codding! ;-)

Related

Generate (pseudo-) base-26 number representation (similar to Excel column names) [duplicate]

How do you convert a numerical number to an Excel column name in C# without using automation getting the value directly from Excel.
Excel 2007 has a possible range of 1 to 16384, which is the number of columns that it supports. The resulting values should be in the form of excel column names, e.g. A, AA, AAA etc.
Here's how I do it:
private string GetExcelColumnName(int columnNumber)
{
string columnName = "";
while (columnNumber > 0)
{
int modulo = (columnNumber - 1) % 26;
columnName = Convert.ToChar('A' + modulo) + columnName;
columnNumber = (columnNumber - modulo) / 26;
}
return columnName;
}
If anyone needs to do this in Excel without VBA, here is a way:
=SUBSTITUTE(ADDRESS(1;colNum;4);"1";"")
where colNum is the column number
And in VBA:
Function GetColumnName(colNum As Integer) As String
Dim d As Integer
Dim m As Integer
Dim name As String
d = colNum
name = ""
Do While (d > 0)
m = (d - 1) Mod 26
name = Chr(65 + m) + name
d = Int((d - m) / 26)
Loop
GetColumnName = name
End Function
Sorry, this is Python instead of C#, but at least the results are correct:
def ColIdxToXlName(idx):
if idx < 1:
raise ValueError("Index is too small")
result = ""
while True:
if idx > 26:
idx, r = divmod(idx - 1, 26)
result = chr(r + ord('A')) + result
else:
return chr(idx + ord('A') - 1) + result
for i in xrange(1, 1024):
print "%4d : %s" % (i, ColIdxToXlName(i))
You might need conversion both ways, e.g from Excel column adress like AAZ to integer and from any integer to Excel. The two methods below will do just that. Assumes 1 based indexing, first element in your "arrays" are element number 1.
No limits on size here, so you can use adresses like ERROR and that would be column number 2613824 ...
public static string ColumnAdress(int col)
{
if (col <= 26) {
return Convert.ToChar(col + 64).ToString();
}
int div = col / 26;
int mod = col % 26;
if (mod == 0) {mod = 26;div--;}
return ColumnAdress(div) + ColumnAdress(mod);
}
public static int ColumnNumber(string colAdress)
{
int[] digits = new int[colAdress.Length];
for (int i = 0; i < colAdress.Length; ++i)
{
digits[i] = Convert.ToInt32(colAdress[i]) - 64;
}
int mul=1;int res=0;
for (int pos = digits.Length - 1; pos >= 0; --pos)
{
res += digits[pos] * mul;
mul *= 26;
}
return res;
}
I discovered an error in my first post, so I decided to sit down and do the the math. What I found is that the number system used to identify Excel columns is not a base 26 system, as another person posted. Consider the following in base 10. You can also do this with the letters of the alphabet.
Space:.........................S1, S2, S3 : S1, S2, S3
....................................0, 00, 000 :.. A, AA, AAA
....................................1, 01, 001 :.. B, AB, AAB
.................................... …, …, … :.. …, …, …
....................................9, 99, 999 :.. Z, ZZ, ZZZ
Total states in space: 10, 100, 1000 : 26, 676, 17576
Total States:...............1110................18278
Excel numbers columns in the individual alphabetical spaces using base 26. You can see that in general, the state space progression is a, a^2, a^3, … for some base a, and the total number of states is a + a^2 + a^3 + … .
Suppose you want to find the total number of states A in the first N spaces. The formula for doing so is A = (a)(a^N - 1 )/(a-1). This is important because we need to find the space N that corresponds to our index K. If I want to find out where K lies in the number system I need to replace A with K and solve for N. The solution is N = log{base a} (A (a-1)/a +1). If I use the example of a = 10 and K = 192, I know that N = 2.23804… . This tells me that K lies at the beginning of the third space since it is a little greater than two.
The next step is to find exactly how far in the current space we are. To find this, subtract from K the A generated using the floor of N. In this example, the floor of N is two. So, A = (10)(10^2 – 1)/(10-1) = 110, as is expected when you combine the states of the first two spaces. This needs to be subtracted from K because these first 110 states would have already been accounted for in the first two spaces. This leaves us with 82 states. So, in this number system, the representation of 192 in base 10 is 082.
The C# code using a base index of zero is
private string ExcelColumnIndexToName(int Index)
{
string range = string.Empty;
if (Index < 0 ) return range;
int a = 26;
int x = (int)Math.Floor(Math.Log((Index) * (a - 1) / a + 1, a));
Index -= (int)(Math.Pow(a, x) - 1) * a / (a - 1);
for (int i = x+1; Index + i > 0; i--)
{
range = ((char)(65 + Index % a)).ToString() + range;
Index /= a;
}
return range;
}
//Old Post
A zero-based solution in C#.
private string ExcelColumnIndexToName(int Index)
{
string range = "";
if (Index < 0 ) return range;
for(int i=1;Index + i > 0;i=0)
{
range = ((char)(65 + Index % 26)).ToString() + range;
Index /= 26;
}
if (range.Length > 1) range = ((char)((int)range[0] - 1)).ToString() + range.Substring(1);
return range;
}
This answer is in javaScript:
function getCharFromNumber(columnNumber){
var dividend = columnNumber;
var columnName = "";
var modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = String.fromCharCode(65 + modulo).toString() + columnName;
dividend = parseInt((dividend - modulo) / 26);
}
return columnName;
}
Easy with recursion.
public static string GetStandardExcelColumnName(int columnNumberOneBased)
{
int baseValue = Convert.ToInt32('A');
int columnNumberZeroBased = columnNumberOneBased - 1;
string ret = "";
if (columnNumberOneBased > 26)
{
ret = GetStandardExcelColumnName(columnNumberZeroBased / 26) ;
}
return ret + Convert.ToChar(baseValue + (columnNumberZeroBased % 26) );
}
I'm surprised all of the solutions so far contain either iteration or recursion.
Here's my solution that runs in constant time (no loops). This solution works for all possible Excel columns and checks that the input can be turned into an Excel column. Possible columns are in the range [A, XFD] or [1, 16384]. (This is dependent on your version of Excel)
private static string Turn(uint col)
{
if (col < 1 || col > 16384) //Excel columns are one-based (one = 'A')
throw new ArgumentException("col must be >= 1 and <= 16384");
if (col <= 26) //one character
return ((char)(col + 'A' - 1)).ToString();
else if (col <= 702) //two characters
{
char firstChar = (char)((int)((col - 1) / 26) + 'A' - 1);
char secondChar = (char)(col % 26 + 'A' - 1);
if (secondChar == '#') //Excel is one-based, but modulo operations are zero-based
secondChar = 'Z'; //convert one-based to zero-based
return string.Format("{0}{1}", firstChar, secondChar);
}
else //three characters
{
char firstChar = (char)((int)((col - 1) / 702) + 'A' - 1);
char secondChar = (char)((col - 1) / 26 % 26 + 'A' - 1);
char thirdChar = (char)(col % 26 + 'A' - 1);
if (thirdChar == '#') //Excel is one-based, but modulo operations are zero-based
thirdChar = 'Z'; //convert one-based to zero-based
return string.Format("{0}{1}{2}", firstChar, secondChar, thirdChar);
}
}
Same implementation in Java
public String getExcelColumnName (int columnNumber)
{
int dividend = columnNumber;
int i;
String columnName = "";
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
i = 65 + modulo;
columnName = new Character((char)i).toString() + columnName;
dividend = (int)((dividend - modulo) / 26);
}
return columnName;
}
int nCol = 127;
string sChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string sCol = "";
while (nCol >= 26)
{
int nChar = nCol % 26;
nCol = (nCol - nChar) / 26;
// You could do some trick with using nChar as offset from 'A', but I am lazy to do it right now.
sCol = sChars[nChar] + sCol;
}
sCol = sChars[nCol] + sCol;
Update: Peter's comment is right. That's what I get for writing code in the browser. :-) My solution was not compiling, it was missing the left-most letter and it was building the string in reverse order - all now fixed.
Bugs aside, the algorithm is basically converting a number from base 10 to base 26.
Update 2: Joel Coehoorn is right - the code above will return AB for 27. If it was real base 26 number, AA would be equal to A and the next number after Z would be BA.
int nCol = 127;
string sChars = "0ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string sCol = "";
while (nCol > 26)
{
int nChar = nCol % 26;
if (nChar == 0)
nChar = 26;
nCol = (nCol - nChar) / 26;
sCol = sChars[nChar] + sCol;
}
if (nCol != 0)
sCol = sChars[nCol] + sCol;
..And converted to php:
function GetExcelColumnName($columnNumber) {
$columnName = '';
while ($columnNumber > 0) {
$modulo = ($columnNumber - 1) % 26;
$columnName = chr(65 + $modulo) . $columnName;
$columnNumber = (int)(($columnNumber - $modulo) / 26);
}
return $columnName;
}
Just throwing in a simple two-line C# implementation using recursion, because all the answers here seem far more complicated than necessary.
/// <summary>
/// Gets the column letter(s) corresponding to the given column number.
/// </summary>
/// <param name="column">The one-based column index. Must be greater than zero.</param>
/// <returns>The desired column letter, or an empty string if the column number was invalid.</returns>
public static string GetColumnLetter(int column) {
if (column < 1) return String.Empty;
return GetColumnLetter((column - 1) / 26) + (char)('A' + (column - 1) % 26);
}
Although there are already a bunch of valid answers1, none get into the theory behind it.
Excel column names are bijective base-26 representations of their number. This is quite different than an ordinary base 26 (there is no leading zero), and I really recommend reading the Wikipedia entry to grasp the differences. For example, the decimal value 702 (decomposed in 26*26 + 26) is represented in "ordinary" base 26 by 110 (i.e. 1x26^2 + 1x26^1 + 0x26^0) and in bijective base-26 by ZZ (i.e. 26x26^1 + 26x26^0).
Differences aside, bijective numeration is a positional notation, and as such we can perform conversions using an iterative (or recursive) algorithm which on each iteration finds the digit of the next position (similarly to an ordinary base conversion algorithm).
The general formula to get the digit at the last position (the one indexed 0) of the bijective base-k representation of a decimal number m is (f being the ceiling function minus 1):
m - (f(m / k) * k)
The digit at the next position (i.e. the one indexed 1) is found by applying the same formula to the result of f(m / k). We know that for the last digit (i.e. the one with the highest index) f(m / k) is 0.
This forms the basis for an iteration that finds each successive digit in bijective base-k of a decimal number. In pseudo-code it would look like this (digit() maps a decimal integer to its representation in the bijective base -- e.g. digit(1) would return A in bijective base-26):
fun conv(m)
q = f(m / k)
a = m - (q * k)
if (q == 0)
return digit(a)
else
return conv(q) + digit(a);
So we can translate this to C#2 to get a generic3 "conversion to bijective base-k" ToBijective() routine:
class BijectiveNumeration {
private int baseK;
private Func<int, char> getDigit;
public BijectiveNumeration(int baseK, Func<int, char> getDigit) {
this.baseK = baseK;
this.getDigit = getDigit;
}
public string ToBijective(double decimalValue) {
double q = f(decimalValue / baseK);
double a = decimalValue - (q * baseK);
return ((q > 0) ? ToBijective(q) : "") + getDigit((int)a);
}
private static double f(double i) {
return (Math.Ceiling(i) - 1);
}
}
Now for conversion to bijective base-26 (our "Excel column name" use case):
static void Main(string[] args)
{
BijectiveNumeration bijBase26 = new BijectiveNumeration(
26,
(value) => Convert.ToChar('A' + (value - 1))
);
Console.WriteLine(bijBase26.ToBijective(1)); // prints "A"
Console.WriteLine(bijBase26.ToBijective(26)); // prints "Z"
Console.WriteLine(bijBase26.ToBijective(27)); // prints "AA"
Console.WriteLine(bijBase26.ToBijective(702)); // prints "ZZ"
Console.WriteLine(bijBase26.ToBijective(16384)); // prints "XFD"
}
Excel's maximum column index is 16384 / XFD, but this code will convert any positive number.
As an added bonus, we can now easily convert to any bijective base. For example for bijective base-10:
static void Main(string[] args)
{
BijectiveNumeration bijBase10 = new BijectiveNumeration(
10,
(value) => value < 10 ? Convert.ToChar('0'+value) : 'A'
);
Console.WriteLine(bijBase10.ToBijective(1)); // prints "1"
Console.WriteLine(bijBase10.ToBijective(10)); // prints "A"
Console.WriteLine(bijBase10.ToBijective(123)); // prints "123"
Console.WriteLine(bijBase10.ToBijective(20)); // prints "1A"
Console.WriteLine(bijBase10.ToBijective(100)); // prints "9A"
Console.WriteLine(bijBase10.ToBijective(101)); // prints "A1"
Console.WriteLine(bijBase10.ToBijective(2010)); // prints "19AA"
}
1 This generic answer can eventually be reduced to the other, correct, specific answers, but I find it hard to fully grasp the logic of the solutions without the formal theory behind bijective numeration in general. It also proves its correctness nicely. Additionally, several similar questions link back to this one, some being language-agnostic or more generic. That's why I thought the addition of this answer was warranted, and that this question was a good place to put it.
2 C# disclaimer: I implemented an example in C# because this is what is asked here, but I have never learned nor used the language. I have verified it does compile and run, but please adapt it to fit the language best practices / general conventions, if necessary.
3 This example only aims to be correct and understandable ; it could and should be optimized would performance matter (e.g. with tail-recursion -- but that seems to require trampolining in C#), and made safer (e.g. by validating parameters).
I wanted to throw in my static class I use, for interoping between col index and col Label. I use a modified accepted answer for my ColumnLabel Method
public static class Extensions
{
public static string ColumnLabel(this int col)
{
var dividend = col;
var columnLabel = string.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnLabel = Convert.ToChar(65 + modulo).ToString() + columnLabel;
dividend = (int)((dividend - modulo) / 26);
}
return columnLabel;
}
public static int ColumnIndex(this string colLabel)
{
// "AD" (1 * 26^1) + (4 * 26^0) ...
var colIndex = 0;
for(int ind = 0, pow = colLabel.Count()-1; ind < colLabel.Count(); ++ind, --pow)
{
var cVal = Convert.ToInt32(colLabel[ind]) - 64; //col A is index 1
colIndex += cVal * ((int)Math.Pow(26, pow));
}
return colIndex;
}
}
Use this like...
30.ColumnLabel(); // "AD"
"AD".ColumnIndex(); // 30
private String getColumn(int c) {
String s = "";
do {
s = (char)('A' + (c % 26)) + s;
c /= 26;
} while (c-- > 0);
return s;
}
Its not exactly base 26, there is no 0 in the system. If there was, 'Z' would be followed by 'BA' not by 'AA'.
if you just want it for a cell formula without code, here's a formula for it:
IF(COLUMN()>=26,CHAR(ROUND(COLUMN()/26,1)+64)&CHAR(MOD(COLUMN(),26)+64),CHAR(COLUMN()+64))
In Delphi (Pascal):
function GetExcelColumnName(columnNumber: integer): string;
var
dividend, modulo: integer;
begin
Result := '';
dividend := columnNumber;
while dividend > 0 do begin
modulo := (dividend - 1) mod 26;
Result := Chr(65 + modulo) + Result;
dividend := (dividend - modulo) div 26;
end;
end;
A little late to the game, but here's the code I use (in C#):
private static readonly string _Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static int ColumnNameParse(string value)
{
// assumes value.Length is [1,3]
// assumes value is uppercase
var digits = value.PadLeft(3).Select(x => _Alphabet.IndexOf(x));
return digits.Aggregate(0, (current, index) => (current * 26) + (index + 1));
}
In perl, for an input of 1 (A), 27 (AA), etc.
sub excel_colname {
my ($idx) = #_; # one-based column number
--$idx; # zero-based column index
my $name = "";
while ($idx >= 0) {
$name .= chr(ord("A") + ($idx % 26));
$idx = int($idx / 26) - 1;
}
return scalar reverse $name;
}
Though I am late to the game, Graham's answer is far from being optimal. Particularly, you don't have to use the modulo, call ToString() and apply (int) cast. Considering that in most cases in C# world you would start numbering from 0, here is my revision:
public static string GetColumnName(int index) // zero-based
{
const byte BASE = 'Z' - 'A' + 1;
string name = String.Empty;
do
{
name = Convert.ToChar('A' + index % BASE) + name;
index = index / BASE - 1;
}
while (index >= 0);
return name;
}
More than 30 solutions already, but here's my one-line C# solution...
public string IntToExcelColumn(int i)
{
return ((i<16926? "" : ((char)((((i/26)-1)%26)+65)).ToString()) + (i<2730? "" : ((char)((((i/26)-1)%26)+65)).ToString()) + (i<26? "" : ((char)((((i/26)-1)%26)+65)).ToString()) + ((char)((i%26)+65)));
}
After looking at all the supplied Versions here, I decided to do one myself, using recursion.
Here is my vb.net Version:
Function CL(ByVal x As Integer) As String
If x >= 1 And x <= 26 Then
CL = Chr(x + 64)
Else
CL = CL((x - x Mod 26) / 26) & Chr((x Mod 26) + 1 + 64)
End If
End Function
Refining the original solution (in C#):
public static class ExcelHelper
{
private static Dictionary<UInt16, String> l_DictionaryOfColumns;
public static ExcelHelper() {
l_DictionaryOfColumns = new Dictionary<ushort, string>(256);
}
public static String GetExcelColumnName(UInt16 l_Column)
{
UInt16 l_ColumnCopy = l_Column;
String l_Chars = "0ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String l_rVal = "";
UInt16 l_Char;
if (l_DictionaryOfColumns.ContainsKey(l_Column) == true)
{
l_rVal = l_DictionaryOfColumns[l_Column];
}
else
{
while (l_ColumnCopy > 26)
{
l_Char = l_ColumnCopy % 26;
if (l_Char == 0)
l_Char = 26;
l_ColumnCopy = (l_ColumnCopy - l_Char) / 26;
l_rVal = l_Chars[l_Char] + l_rVal;
}
if (l_ColumnCopy != 0)
l_rVal = l_Chars[l_ColumnCopy] + l_rVal;
l_DictionaryOfColumns.ContainsKey(l_Column) = l_rVal;
}
return l_rVal;
}
}
Here is an Actionscript version:
private var columnNumbers:Array = ['A', 'B', 'C', 'D', 'E', 'F' , 'G', 'H', 'I', 'J', 'K' ,'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
private function getExcelColumnName(columnNumber:int) : String{
var dividend:int = columnNumber;
var columnName:String = "";
var modulo:int;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = columnNumbers[modulo] + columnName;
dividend = int((dividend - modulo) / 26);
}
return columnName;
}
JavaScript Solution
/**
* Calculate the column letter abbreviation from a 1 based index
* #param {Number} value
* #returns {string}
*/
getColumnFromIndex = function (value) {
var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
var remainder, result = "";
do {
remainder = value % 26;
result = base[(remainder || 26) - 1] + result;
value = Math.floor(value / 26);
} while (value > 0);
return result;
};
These my codes to convert specific number (index start from 1) to Excel Column.
public static string NumberToExcelColumn(uint number)
{
uint originalNumber = number;
uint numChars = 1;
while (Math.Pow(26, numChars) < number)
{
numChars++;
if (Math.Pow(26, numChars) + 26 >= number)
{
break;
}
}
string toRet = "";
uint lastValue = 0;
do
{
number -= lastValue;
double powerVal = Math.Pow(26, numChars - 1);
byte thisCharIdx = (byte)Math.Truncate((columnNumber - 1) / powerVal);
lastValue = (int)powerVal * thisCharIdx;
if (numChars - 2 >= 0)
{
double powerVal_next = Math.Pow(26, numChars - 2);
byte thisCharIdx_next = (byte)Math.Truncate((columnNumber - lastValue - 1) / powerVal_next);
int lastValue_next = (int)Math.Pow(26, numChars - 2) * thisCharIdx_next;
if (thisCharIdx_next == 0 && lastValue_next == 0 && powerVal_next == 26)
{
thisCharIdx--;
lastValue = (int)powerVal * thisCharIdx;
}
}
toRet += (char)((byte)'A' + thisCharIdx + ((numChars > 1) ? -1 : 0));
numChars--;
} while (numChars > 0);
return toRet;
}
My Unit Test:
[TestMethod]
public void Test()
{
Assert.AreEqual("A", NumberToExcelColumn(1));
Assert.AreEqual("Z", NumberToExcelColumn(26));
Assert.AreEqual("AA", NumberToExcelColumn(27));
Assert.AreEqual("AO", NumberToExcelColumn(41));
Assert.AreEqual("AZ", NumberToExcelColumn(52));
Assert.AreEqual("BA", NumberToExcelColumn(53));
Assert.AreEqual("ZZ", NumberToExcelColumn(702));
Assert.AreEqual("AAA", NumberToExcelColumn(703));
Assert.AreEqual("ABC", NumberToExcelColumn(731));
Assert.AreEqual("ACQ", NumberToExcelColumn(771));
Assert.AreEqual("AYZ", NumberToExcelColumn(1352));
Assert.AreEqual("AZA", NumberToExcelColumn(1353));
Assert.AreEqual("AZB", NumberToExcelColumn(1354));
Assert.AreEqual("BAA", NumberToExcelColumn(1379));
Assert.AreEqual("CNU", NumberToExcelColumn(2413));
Assert.AreEqual("GCM", NumberToExcelColumn(4823));
Assert.AreEqual("MSR", NumberToExcelColumn(9300));
Assert.AreEqual("OMB", NumberToExcelColumn(10480));
Assert.AreEqual("ULV", NumberToExcelColumn(14530));
Assert.AreEqual("XFD", NumberToExcelColumn(16384));
}
Sorry, this is Python instead of C#, but at least the results are correct:
def excel_column_number_to_name(column_number):
output = ""
index = column_number-1
while index >= 0:
character = chr((index%26)+ord('A'))
output = output + character
index = index/26 - 1
return output[::-1]
for i in xrange(1, 1024):
print "%4d : %s" % (i, excel_column_number_to_name(i))
Passed these test cases:
Column Number: 494286 => ABCDZ
Column Number: 27 => AA
Column Number: 52 => AZ
For what it is worth, here is Graham's code in Powershell:
function ConvertTo-ExcelColumnID {
param (
[parameter(Position = 0,
HelpMessage = "A 1-based index to convert to an excel column ID. e.g. 2 => 'B', 29 => 'AC'",
Mandatory = $true)]
[int]$index
);
[string]$result = '';
if ($index -le 0 ) {
return $result;
}
while ($index -gt 0) {
[int]$modulo = ($index - 1) % 26;
$character = [char]($modulo + [int][char]'A');
$result = $character + $result;
[int]$index = ($index - $modulo) / 26;
}
return $result;
}
Another VBA way
Public Function GetColumnName(TargetCell As Range) As String
GetColumnName = Split(CStr(TargetCell.Cells(1, 1).Address), "$")(1)
End Function
Here's my super late implementation in PHP. This one's recursive. I wrote it just before I found this post. I wanted to see if others had solved this problem already...
public function GetColumn($intNumber, $strCol = null) {
if ($intNumber > 0) {
$intRem = ($intNumber - 1) % 26;
$strCol = $this->GetColumn(intval(($intNumber - $intRem) / 26), sprintf('%s%s', chr(65 + $intRem), $strCol));
}
return $strCol;
}

Solving Mathematical logics, placing digits in third number from digits of first and second number

I have two numbers.
First Number is 2875 &
Second Number is 852145
Now I need a program which create third number.
Third Number will be 2885725145
The logic is
First digit of third number is first digit of first number.
Second digit of third number is first digit of second number.
Third digit of third number is second digit of first number.
Fourth digit of third number is second digit of second number;
so on.
If any number has remaining digits then that should be appended at last.
I do not want to convert int to string.
int CreateThirdNumber(int firstNumber, int secondNumber)
{
}
So can anyone suggest me any solution to this problem?
I do not want to convert int to string.
Why?
Without converting to string
Use Modulus and Division operator.
With converting to string
Convert them to string. Use .Substring() to extract and append value in a string. Convert appended string to integer.
Here's a bit that will give you a lead:
Say you have the number 2875. First, you need to determine it's length, and then, extract the first digit
This can be easily calculated:
int iNumber = 2875;
int i = 10;
int iLength = 0;
while (iNumber % i <= iNumber){
iLength++;
i *= 10;
}
// iNumber is of length iLength, now get the first digit,
// using the fact that the division operator floors the result
int iDigit = iNumber / pow(10, iLength-1);
// Thats it!
First a little advice: if you use int in C#, then the value in your example (2885725145) is bigger than int.MaxValue; (so in this case you should use long instead of int).
Anyway here is the code for your example, without strings.
int i1 = 2875;
int i2 = 852145;
int i3 = 0;
int i1len = (int)Math.Log10(i1) + 1;
int i2len = (int)Math.Log10(i2) + 1;
i3 = Math.Max(i1, i2) % (int)Math.Pow(10, Math.Max(i1len, i2len) - Math.Min(i1len, i2len));
int difference = (i1len - i2len);
if (difference > 0)
i1 /= (int)Math.Pow(10, difference);
else
i2 /= (int)Math.Pow(10, -difference);
for (int i = 0; i < Math.Min(i1len, i2len); i++)
{
i3 += (i2 % 10) * (int)Math.Pow(10, Math.Max(i1len, i2len) - Math.Min(i1len, i2len) + i * 2);
i3 += (i1 % 10) * (int)Math.Pow(10, Math.Max(i1len, i2len) - Math.Min(i1len, i2len) + i * 2 + 1);
i1 /= 10;
i2 /= 10;
}
I don't understand why you don't want to use strings (is it homework?). Anyway this is another possible solution:
long CreateThirdNumber(long firstNumber, long secondNumber)
{
long firstN = firstNumber;
long secondN = secondNumber;
long len1 = (long)Math.Truncate(Math.Log10(firstNumber));
long len2 = (long)Math.Truncate(Math.Log10(secondNumber));
long maxLen = Math.Max(len1, len2);
long result = 0;
long curPow = len1 + len2 + 1;
for (int i = 0; i <= maxLen; i++)
{
if (len1 >= i)
{
long tenPwf = (long)Math.Pow(10, len1 - i);
long firstD = firstN / tenPwf;
firstN = firstN % tenPwf;
result = result + firstD * (long)Math.Pow(10, curPow--);
}
if (len2 >= i)
{
long tenPws = (long)Math.Pow(10, len2 - i);
long secondD = secondN / tenPws;
result = result + secondD * (long)Math.Pow(10, curPow--);
secondN = secondN % tenPws;
}
}
return result;
}
This solves it:
#include <stdio.h>
int main(void)
{
int first = 2875,second = 852145;
unsigned int third =0;
int deci,evenodd ,tmp ,f_dec,s_dec;
f_dec = s_dec =1;
while(first/f_dec != 0 || second/s_dec != 0) {
if(first/f_dec != 0) {
f_dec *=10;
}
if( second/s_dec != 0) {
s_dec *= 10;
}
}
s_dec /=10; f_dec/=10;
deci = s_dec*f_dec*10;
evenodd =0;tmp =0;
while(f_dec != 0 || s_dec !=0 ) {
if(evenodd%2 == 0 && f_dec !=0 ) {
tmp = (first/f_dec);
first -=(tmp*f_dec);
tmp*=deci;
third+=tmp;
f_dec/=10;
deci/=10;
}
if(evenodd%2 != 0 && s_dec != 0) {
tmp= (second/s_dec);
second -=(tmp*s_dec);
//printf("tmp:%d\n",tmp);
tmp*=deci;
third += tmp;
s_dec/=10;
deci/=10;
}
evenodd++;
}
printf("third:%u\ncorrct2885725145\n",third);
return 0;
}
output:
third:2885725145
corrct2885725145
#include <stdio.h>
long long int CreateThirdNumber(int firstNumber, int secondNumber){
char first[11],second[11],third[21];
char *p1=first, *p2=second, *p3=third;
long long int ret;
sprintf(first, "%d", firstNumber);
sprintf(second, "%d", secondNumber);
while(1){
if(*p1)
*p3++=*p1++;
if(*p2)
*p3++=*p2++;
if(*p1 == '\0' && *p2 == '\0')
break;
}
*p3='\0';
sscanf(third, "%lld", &ret);
return ret;
}
int main(){
int first = 2875;
int second = 852145;
long long int third;
third = CreateThirdNumber(first, second);
printf("%lld\n", third);
return 0;
}

How to convert string into int array in C#

I am making a credit card validator program in which I am asking for a string which is going to be a 16 digit number (credit card #) and I want to convert that into an int array. How do I do that? I need to then multiply every other digit starting from the first digit by 2.
char[] creditNumbers = creditCardNumber.ToCharArray();
creditNumbers[0] = (char)((int)(creditNumbers[0] * 2));
creditNumbers[2] = (char)((int)(creditNumbers[2] * 2));
creditNumbers[4] = (char)((int)(creditNumbers[4] * 2));
creditNumbers[6] = (char)((int)(creditNumbers[6] * 2));
creditNumbers[8] = (char)((int)(creditNumbers[8] * 2));
This is what I made so far but my casting is not done properly. How do I fix the problem?
To just get the int array, I would do this:
creditCardNumber.Select(c => int.Parse(c.ToString())).ToArray()
To check the number using the Luhn algorithm, you could do this:
bool IsValid(string creditCardNumber)
{
var sum = creditCardNumber.Reverse()
.Select(TransformDigit)
.Sum();
return sum % 10 == 0;
}
int TransformDigit(char digitChar, int position)
{
int digit = int.Parse(digitChar.ToString());
if (position % 2 == 1)
digit *= 2;
return digit % 10 + digit / 10;
}
var intArray = creditCardNumber.ToCharArray().Select(o => int.Parse(o.ToString())).ToArray();
var result = new List<int>();
for(int i=0; i<intArray.Length; i++){
if((i % 2) == 0)
result.Add(intArray[i] * 2);
else
result.Add(intArray[i]);
}
Console.Write(string.Concat(result.Select(o => o.ToString())));

Round any n-digit number to (n-1) zero-digits

Sorry hard to formulate.
I need to round like this:
12 -> 10
152 -> 200
1538 -> 2000
25000 -> 30000
etc.
Twisting my head, but can't see how to make this. Must work for any n number of digits. Anyone got an elegant method for it?
c# or vb.net
How about this:
double num = 152;
int pow = (int)Math.Log10(num);
int factor = (int)Math.Pow(10, pow);
double temp = num / factor;
double result = Math.Round(temp) * factor;
I think you should try with something like this:
public int Round( int number)
{
int power = number.ToString().Length - 1;
int sz = Math.Pow(10, power);
int rounded = (int)Math.Round( number / sz );
return rounded * sz;
}
The idea is to get the size of the nearest 10 power, available by the length of the number expressed as a string. Then divide the number by that power, leaving it like 1,2 and then round it using the Math.Round method and restore the size by remultiplying it to the power.
Much like the previous answer...
I would do it this way:
double d = 25000;
int power = d.ToString().Length - 1;
double multipler = Math.Pow(10,power);
d = Math.Round(d / multipler) * multipler;
Console.WriteLine(d);
One of the way could be
Convert the number to Decimal
Divide it by 10^(n-1) (where n is number of digits)
Now use round function (Decimal.Round)
Multiply again by 10^(n-1)
Divide the number by 10n and round the result, then multiply the result back with 10n;
int MyRound(int num)
{
double divisor = Math.Pow(10, num.ToString().Length - 1);
return (int)(Math.Round(num / divisor, MidpointRounding.AwayFromZero) * divisor);
}
Note that we should use MidpointRounding.AwayFromZero when rounding because of the default banker's rounding.
int MakeOneSigFig(int value)
{
int neg = 1;
if(value <= 10 && value >= -10) { return value; }
if(value == int.MinValue) { value = int.MaxValue; neg = -1; }
if(value < 0) { value = -value; neg = -1; }
int mult = 10; // start at 10 because we've got 'firstDigit = value / 10' below
while(value > 99) { value /= 10; mult *= 10; }
int firstDigit = value / 10;
if(value % 10 >= 5) firstDigit++;
return neg * firstDigit * mult;
}
This is equivalent to MidpointRounding.AwayFromZero. This method doesn't do any double math or string conversions. If you didn't want to loop, you could replace that with the if block below. That would be more efficient, but more code and not quite as easy to read.
if(value < 100) { mult = 10; }
else if(value < 1000) { mult = 100; value /= 10; }
else if(value < 10000) { mult = 1000; value /= 100; }
else if(value < 100000) { mult = 10000; value /= 1000; }
// etc.

round up given number in c#

I want round up given numbers in c#
Ex:
round(25)=50
round(250) = 500
round(725) = 1000
round(1200) = 1500
round(7125) = 7500
round(8550) = 9000
Most of your data suggests that you want to round up to the nearest multiple of 500. This would be done by
int round(int input)
{
return (int)(500 * Math.Ceiling(input / 500.0));
}
The rounding of 25 to 50 will not work, though.
Another guess would be that you want your rounding to depend on the size of the number being rounded. The following function would round 25 to 50, 250 to 500, 0.025 to 0.05, and 2500 to 5000. Maybe you can work from there.
double round(double input)
{
double scale = Math.Floor(Math.Log10(input));
double step = 5 * Math.Pow(10, scale);
return step * Math.Ceiling(input/step);
}
Depending on what you need, this could be a nice, reusable solution.
static int RoundUpWeird(int rawNr)
{
if (rawNr < 100 && rawNr > -100)
return RoundUpToNext50(rawNr);
else
return RoundUpToNext500(rawNr);
}
static int RoundUpToNext50(int rawNr)
{
return RoundUpToNext(rawNr, 50);
}
static int RoundUpToNext500(int rawNr)
{
return RoundUpToNext(rawNr, 500);
}
static int RoundUpToNext(int rawNr, int next)
{
int result;
int remainder;
if ((remainder = rawNr % next) != 0)
{
if (rawNr >= 0)
result = RoundPositiveToNext(rawNr, next, remainder);
else
result = RoundNegativeToNext(rawNr, remainder);
if (result < rawNr)
throw new OverflowException("round(Number) > Int.MaxValue!");
return result;
}
return rawNr;
}
private static int RoundNegativeToNext(int rawNr, int remainder)
{
return rawNr - remainder;
}
private static int RoundPositiveToNext(int rawNr, int next, int remainder)
{
return rawNr + next - remainder;
}
This code should work according to the rules I can gather:
public static double Round(double val)
{
int baseNum = val <= 100 ? 100 : 1000;
double factor = 0.5;
double v = val / baseNum;
var res = Math.Ceiling(v / factor) / (1 / factor) * baseNum;
return res;
}
This should work. And also for numbers greater than those you wrote:
int round(int value)
{
int i = 1;
while (value > i)
{
i *= 10;
}
return (int)(0.05 * i * Math.Ceiling(value / (0.05 * i)));
}

Categories

Resources