Skip to content

Instantly share code, notes, and snippets.

@rmccullagh
Last active December 1, 2016 02:15
Show Gist options
  • Save rmccullagh/d2afdefc51f46a498a1776b11b85dffb to your computer and use it in GitHub Desktop.
Save rmccullagh/d2afdefc51f46a498a1776b11b85dffb to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pangea
{
class Program
{
public static string TrimNumbers(string s, int maxCharCount)
{
string output = "";
if (s.Length == maxCharCount)
return s;
for(int i = 0; i < maxCharCount; i++)
{
if(i == maxCharCount - 1)
{
// Check for last character being a comma
if(s[i] == ',')
{
break;
}
// Check to see if this is a floating point
if(i + 1 < s.Length && s[i + 1] == '.')
{
int position = i;
while(s[--position] != ',' && position >= 0) {
output = s.Remove(i - 1);
}
// Remove last comma
// Handle edge cases
if(position >= 0)
output = s.Remove(position);
break;
}
}
output += s[i];
}
return output;
}
static void Main(string[] args)
{
string input = "4.5,6.76666666666666";
string expectedOutput = "4.5";
string decimalOutput = TrimNumbers(input, 5);
if (decimalOutput != expectedOutput)
{
Console.WriteLine("Error: Invalid output, got " + "\"" +
decimalOutput + "\"" + ", expecting " + "\"" + expectedOutput + "\"");
}
Console.WriteLine(decimalOutput);
input = "1,2,3";
expectedOutput = "1,2,3";
string wholeNumberOutput = TrimNumbers(input, 5);
if (wholeNumberOutput != expectedOutput)
{
Console.WriteLine("Error: Invalid output, got " + "\"" +
wholeNumberOutput + "\"" + ", expecting " + "\"" + expectedOutput + "\"");
}
Console.WriteLine(wholeNumberOutput);
Console.Read();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment