Skip to content

Number to Money ✅

This is a project intended to give you the opportunity to show off your design, problem solving and testing skills. Your solution should be as complete and unit tested as possible, we want to see a first simple pass at how you think and how you work. The problem is intended to take a couple of hours at most to complete.

Code Exercise - Write a number prettifier: Write tested code (in any OO language, such as C# or Java) that accepts a numeric type and returns a truncated, "prettified" string version. The prettified version should include one number after the decimal when the truncated number is not an integer. It should prettify numbers greater than 6 digits and support millions, billions and trillions.

::: tip 💡 Think of numbers in power

  • \(1 \times 1000^0\)
  • \(1 \times 1000^1\)
  • \(1 \times 1000^2\) = M
  • \(1 \times 1000^3\) = B
  • \(1 \times 1000^4\) = T :::
input: 1000000
output: 1M

input: 2500000.34
output: 2.5M

input: 532
output: 532

input: 1123456789
output: 1.1B

input: 9487634567534
output: 9.5T

C# Solution

using System;
using System.Collections.Generic;
using System.Text;

namespace Algorithms.Simple
{
  public class NumberToMoney
  {
    public static string Convert(double num)
    {
      const int ConversionBase = 1000;
      string[] powers = { "", "", "M", "B", "T" };
      bool isNegative = num < 0 ? true : false;

      int power = 0;

      while (Math.Abs(num) >= ConversionBase)
      {
        num = Math.Abs(num) / ConversionBase;
        power++;
      }

      return FormatValue(num, isNegative, powers[power]);
    }

    private static string FormatValue(double num, bool isNegative, string symbol)
    {
      const int FormatDigits = 1;
      var sb = new StringBuilder();
      if (isNegative) sb.Insert(0, "-");
      sb.Append(Math.Round(num, FormatDigits)).Append(symbol);
      return sb.ToString();
    }
  }
}

C# Tests

using Algorithms.Simple;
using Xunit;

namespace AlgorithmTests.Simple
{
  public class NumberToMoneyTests
  {
    [Fact]
    public void Thousand_Test()
    {
      Assert.Equal("532", NumberToMoney.Convert(532));
    }

    [Fact]
    public void Million_Test()
    {
      Assert.Equal("1M", NumberToMoney.Convert(1000000));
    }

    [Fact]
    public void Million_Double_Test()
    {
      Assert.Equal("2.5M", NumberToMoney.Convert(2500000.34));
    }

    [Fact]
    public void Billon_Test()
    {
      Assert.Equal("1.1B", NumberToMoney.Convert(1123456789));
    }

    [Fact]
    public void Trillion_Test()
    {
      Assert.Equal("9.5T", NumberToMoney.Convert(9487634567534));
    }

    [Fact]
    public void Zero_Test()
    {
      Assert.Equal("0", NumberToMoney.Convert(0));
    }

    [Fact]
    public void Negative_Number_Test()
    {
      Assert.Equal("-1M", NumberToMoney.Convert(-1000000));
    }
  }
}

Company: MGC Health