Skip to content

Instantly share code, notes, and snippets.

@gleox
Last active May 7, 2018 10:14
Show Gist options
  • Save gleox/b49cd0fbdf0c887c3838ef2414af4ecc to your computer and use it in GitHub Desktop.
Save gleox/b49cd0fbdf0c887c3838ef2414af4ecc to your computer and use it in GitHub Desktop.
Trim end zero characters for a number string.
using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var sources = new Dictionary<string, string>()
{
["100"] = "100",
["100.000"] = "100",
["0.000"] = "0",
["0.060800"] = "0.0608",
};
foreach (var kv in sources)
{
var source = kv.Key;
var expected = kv.Value;
Output(source, expected);
}
Console.Write("Press any key to exit.");
Console.ReadKey();
}
static void Output(string source, string expected)
{
var actual = TrimEndZero(source);
var indentCount = 12;
var indent = string.Empty.PadRight(indentCount + 3, ' ');
var matched = actual == expected;
Console.WriteLine($"{source.PadRight(indentCount, ' ')} -> {actual}");
Console.WriteLine($"{indent} {expected}");
var prevColor = Console.ForegroundColor;
Console.ForegroundColor = matched ? ConsoleColor.Green : ConsoleColor.Red;
Console.WriteLine($"{indent} {matched}");
Console.ForegroundColor = prevColor;
Console.WriteLine();
}
static string TrimEndZero(string source)
{
var dotPos = -1;
var trimEndCount = 0;
var foundNonZero = false;
var i = source.Length - 1;
while (i != 0)
{
var letter = source[i];
if (!foundNonZero && letter == '0')
{
trimEndCount++;
}
else
{
foundNonZero = true;
}
if (letter == '.')
{
dotPos = i;
}
i--;
}
// example: 100
if (dotPos < 0)
{
return source;
}
// example: 100.123
if (trimEndCount == 0)
{
return source;
}
var endIndex = source.Length - trimEndCount;
// example: 100.00
if (endIndex - 1 == dotPos)
{
endIndex--;
}
// example: 0.060800
return source.Substring(0, endIndex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment