QUESTION
Write a function to convert an Integer representing a number of bytes (less than or equal to 1 Gigabyte) into an easy to read format, defined as follows:
• Maximum of 3 digits (not counting a decimal point), and a single letter to signify the unit of measure.
• No leading zeroes, or trailing zeroes after a decimal point.
• Be as accurate as possible.
IMPORTANT DETAILS:
• Maximum of 3 digits (not counting a decimal point), and a single letter to signify the unit of measure. Examples:
o 341B = 341B
o 34200B = 34.2K
o 5910000B = 5.91M
o 1000000000B = 1G
• No leading zeroes, or trailing zeroes after a decimal point. Examples:
o 34K, not 034K
o 7.2M, not 7.20M
• Be as accurate as possible. Example:
o 54123B = 54.1K, not 54K
• Note: For this problem, 1000 bytes =
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Pretty Number Formatting.
Created Date : 01-02-2013
Last Modified :
============================================================================
*/
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdio>
#include <iterator>
using namespace std;
#pragma warning(disable : 4996)
void Help()
{
cout << "Input must between 0 and 1000000000" << endl;
}
void FormatNum(int n)
{
double d;
if (n < 0 || n > 1000000000){
cout << "Invalid input" << endl;
Help();
}
else if (n < 1000){
cout << n << "B" << endl;
}
else if (n < 999500){
d = n / 1000.0;
cout << setprecision(3) << d << 'K' << endl;
}
else if (n < 1000000){
cout << "1M" << endl;
}
else if (n < 999500000){
d = n / 1000000.0;
cout << setprecision(3) << d << 'M' << endl;
}
else{
cout << "1G" << endl;
}
}
void DoTest(int n)
{
cout << "Input " << setw(10) << n << " --- ";
FormatNum(n);
}
int main()
{
int testCases[]
{
341,
34200,
5910000,
1000000000,
34000,
999900,
54123,
1000,
1001,
1019,
1200,
0,
999500,
999400,
999500000,
999400000,
10,
100
};
for (auto i : testCases){
DoTest(i);
}
return 0;
}
Output
Input 341 --- 341B
Input 34200 --- 34.2K
Input 5910000 --- 5.91M
Input 1000000000 --- 1G
Input 34000 --- 34K
Input 999900 --- 1M
Input 54123 --- 54.1K
Input 1000 --- 1K
Input 1001 --- 1K
Input 1019 --- 1.02K
Input 1200 --- 1.2K
Input 0 --- 0B
Input 999500 --- 1M
Input 999400 --- 999K
Input 999500000 --- 1G
Input 999400000 --- 999M
Input 10 --- 10B
Input 100 --- 100B
Press any key to continue . . .