Microsoft Interview Question
SDE1sTeam: Office365
Country: India
Interview Type: In-Person
If you want to do this without libraries, it isn't easy for float numbers because even something like 20.04 will turn into 20.03999999999
If someone can find a way to fix the lines with my 'problems with rounding here' comments, this algorithm will work:
function toStr(num) {
var n = Math.abs(num);
var intPart = Math.floor(n);
var floatPart = n - intPart; // problems with rounding here
var intResult = [];
while (intPart > 0) {
intResult.unshift(String(intPart % 10));
intPart = Math.floor(intPart / 10);
}
var floatResult = [];
while (floatPart > 0) {
floatPart *= 10;
var floatDigit = Math.floor(floatPart);
if (floatDigit >= 1) {
floatResult.push(String(floatDigit));
floatPart -= floatDigit; // problems with rounding here
} else {
floatResult.push('0');
}
}
var result = intResult.slice();
if (floatResult.length > 0) {
result.push('.');
Array.prototype.push.apply(result, floatResult);
}
if (num < 0) {
result.unshift('-');
}
return result;
}
0.5 is hardly any integer... Was it doubles or decimals?
- Chris December 10, 2017