function num(n) {
if (n >= 1000 && n < 10000) return (n/1000).toFixed(3) + "K";
if (n >= 10000 && n < 100000) return (n/1000).toFixed(1) + "K";
if (n >= 100000 && n < 1000000) return (n/1000).toFixed(0) + "K";
if (n >= 1000000 && n < 10000000) return (n/1000000).toFixed(3) + "M";
if (n >= 10000000 && n < 100000000) return (n/1000000).toFixed(1) + "M";
if (n >= 100000000 && n < 1000000000) return (n/1000000).toFixed(0) + "M";
if (n >= 1000000000 && n < 10000000000) return (n/1000000000).toFixed(3) + "B";
if (n >= 10000000000 && n < 100000000000) return (n/1000000000).toFixed(1) + "B";
if (n >= 100000000000 && n < 1000000000000) return (n/1000000000).toFixed(0) + "B";
if (n >= 1000000000000 && n < 10000000000000) return (n/1000000000000).toFixed(3) + "T";
if (n >= 10000000000000 && n < 100000000000000) return (n/1000000000000).toFixed(1) + "T";
if (n >= 100000000000000 && n < 1000000000000000) return (n/1000000000000).toFixed(0) + "T";
return n;
}
Since at some point I'm probably going to be going upwards to the power of hundreds, is there an easier way to do this?
function formatNumber(number) {
var i = 0; units = [ "", "K", "M", "B", "T" ]; // etc
while (number > 1000) {
number /= 1000;
i += 1;
}
return Math.floor(number * 1000) / 1000 + units[i];
}
formatNumber(1234567); // 1.234M
formatNumber(1230567); // 1.23M
This might be faster for very large numbers:
function formatNumber(number) {
var i; units = [ "", "K", "M", "B", "T" ]; // etc
i = Math.round(Math.log(number) / Math.log(10) / 3);
number /= Math.pow(10, i * 3);
return Math.floor(number * 1000) / 1000 + units[i];
}
formatNumber(1234567); // 1.234M
formatNumber(1230567); // 1.23M
My approach here:
function num(n) {
if(n < 1000) {
return n
}
var units = ['K', 'M', 'B', 'T']
for(var i = -1; n >= 1000; i++) {
n /= 1000
}
if(n >= 100) {
return n.toFixed(0) + units[i]
}
if(n >= 10) {
return n.toFixed(1) + units[i]
}
return n.toFixed(3) + units[i]
}
Here's the finished function with help from Halcyon.
function fnum(number) {
var i, x, units = [ "", "K", "M", "B", "T", "Qa", "Qi", "Sx", "Sp", "Oc", "No", "Dc" ];
i = Math.floor(Math.log(number) / Math.log(10) / 3);
x = Math.floor(Math.log(number) / Math.log(10)) % 3;
number /= Math.pow(10, i * 3);
return ((number * 1000) / 1000).toFixed(77 % ((x * 2) + 3)) + units[i];
}
Will return a number from 0 to 999 to 2 decimal places when formatted to 1s and 10s, and 0 decimal places when formatted to 100s, and then add a numerical suffix. Add additional suffixes as required.
fnum(22000); >> 22.00K
fnum(153000000); >> 153M
fnum(2,230,000,000,000); >> 2.23T
function fnum(number) {
var i, x, units = [ "", "K", "M", "B", "T", "Qa", "Qi", "Sx", "Sp", "Oc", "No", "Dc" ];
i = Math.floor(Math.log(number) / Math.log(10) / 3);
x = Math.floor(Math.log(number) / Math.log(10)) % 3;
number /= Math.pow(10, i * 3);
return ((number * 1000) / 1000).toFixed(77 % ((x * 2) + 3)) + units[i];
}
console.log(fnum(22000))
console.log(fnum(153000000))
console.log(fnum(2200000000000))
Related
can anyone come with an idea of how to sort an integer without using an array, and without using string methods as well as sort() method?
for example
input: 642531
output: 123456
I started by writing 2 simple functions - one which checks the length of the number, the other one splits the integer at some point and switches between 2 desired numbers. Below are the 2 functions.
I got stuck with the rest of the solution...
function switchDigits(num, i) { // for input: num=642531, i = 4 returns 624135
let temp = num;
let rest = 0;
for (let j = 0; j < i - 1; j++) {
rest = rest * 10;
rest = rest + temp % 10;
temp = (temp - temp % 10) / 10;
}
let a = temp % 10;
temp = (temp - a) / 10;
let b = temp % 10;
temp = (temp - b) / 10;
temp = Math.pow(10, i - 2) * temp;
temp = temp + 10 * a + b;
temp = Math.pow(10, i - 1) * temp;
temp = temp + rest;
return temp;
}
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
let num = 642534;
let i = checkHowManyDigits(num);
console.log(switchDigits(num));
It actually complicated requirement and so does this answer. It's pure logic and as it is it's a question from a test you should try understanding the logic on your own as a homework.
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
function sortDigit(numOriginal) {
let i = checkHowManyDigits(numOriginal);
let minCount = 0;
let min = 10;
let num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d < min) {
min = d;
minCount = 0;
} else if (d === min) {
minCount++;
}
}
let result = 0;
while (minCount >= 0) {
result += min * Math.pow(10, i - minCount - 1);
minCount--;
}
let newNum = 0;
num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d !== min) {
newNum = newNum * 10 + d;
}
}
if (newNum == 0) return result;
else return result += sortDigit(newNum);
}
console.log(sortDigit(642531));
You could have a look to greater and smaller pairs, like
64
46
The delta is 18, which gets an idea if you compare other pairs, like
71
17
where the delta is 54. Basically any difference of two digits is a multiple of 9.
This in mind, you get a function for taking a single digit out of a number and a single loop who is sorting the digits by using the calculated delta and subtract the value, adjusted by the place.
function sort(number) {
const
getDigit = e => Math.floor(number / 10 ** e) % 10,
l = Math.ceil(Math.log10(number)) - 1;
let e = l;
while (e--) {
const
left = getDigit(e + 1),
right = getDigit(e);
if (left <= right) continue;
number += (right - left) * 9 * 10 ** e;
e = l;
}
return number;
}
console.log(sort(17)); // 17
console.log(sort(71)); // 17
console.log(sort(642531)); // 123456
console.log(sort(987123654)); // 123456789
So eventually I found the best solution.
*This solution is based on a Java solution I found in StackOverFlow forums.
let store = 0;
function getReducedNumbr(number, digit) {
console.log("Remove " + digit + " from " + number);
let newNumber = 0;
let repeateFlag = false;
while (number>0) {
let t = number % 10;
if (t !== digit) {
newNumber = (newNumber * 10) + t;
} else if (t == digit) {
if (repeateFlag) {
console.log(("Repeated min digit " + t + " found. Store is : " + store));
store = (store * 10) + t;
console.log("Repeated min digit " + t + " added to store. Updated store is : " + store);
} else {
repeateFlag = true;
}
}
number = Math.floor(number / 10);
}
console.log("Reduced number is : " + newNumber);
return newNumber;}
function sortNum(num) {
let number = num;
let original = number;
let digit;
while (number > 0) {
digit = number % 10;
console.log("Last digit is : " + digit + " of number : " + number);
temp = Math.floor(number/10);
while (temp > 0) {
console.log("subchunk is " + temp);
t = temp % 10;
if (t < digit) {
digit = t;
}
temp = Math.floor(temp/10);
}
console.log("Smallest digit in " + number + " is " + digit);
store = (store * 10) + digit;
console.log("store is : " + store);
number = getReducedNumbr(number, digit);
}
console.log(("Ascending order of " + original + " is " + store));
return store;
}
console.log(sortNum(4214173));
you can see how it works here https://jsfiddle.net/9dpm14fL/1/
the code should be able to handle any amount up to 20000, For example, suppose the Entered amount is 2600 when the balance in the card is 3000. Will output following :
New Balance - 400
Notes:
2000 * 1
500 * 1
100 * 1
(only three banknotes 2000, 500, 100) and the cash limit is 20000
I am new in the javascript world, and I am not able to write the code, could anyone help me out??? please!
var h = 5;
var f = 2;
var t = 1;
var ifAmtLessThn2000 = ifAmtLessThn2000(n) {
var temp;
if (n < 500) {
h += (n / 100);
return {
h
}
} else if (n >= 500 && n < 2000) {
f += n / 500;
h += (n - 500) / 100;
return {
h,
f
}
} else {
temp = n - 1500;
if (temp < 500) {
h += (temp / 100);
return {
h
}
console.log('hundred : ' + h);
} else {
f += 1;
h += (temp - 500) / 100;
console.log('five hundred : ' + f);
console.log('hundred : ' + h);
return {
f,
h
}
}
}
}
var ifAmtGreaterthan2000 = (n) => {
var h = 0;
var f = 0;
var t = 0;
var tt = 0;
var temp;
if (n < 2000) {
tt += (n / 2000);
}
else if (n >= 2000 && n < 10000) {
f += n / 500;
h += (n - 500) / 100;
}
else {
temp = n - 1500;
if (temp < 500) {
h += (temp / 100);
}
else {
f += 1;
h += (temp - 500) / 100;
}
}
}
var checkAmt = (n) => {
if (n < 100 || (n % 100) > 0) {
console.log("Invalid Amount : less than 100 ");
} else {
if (n > 20000) {
console.log("ATM Cash Limit exceeds.");
} else {
if (n <= 2500) {
ifAmtLessThn2500(n);
console.log(h + " x 100");
console.log(f + " x 500");
} else {
temp = n - 2500;
t += temp / 1000;
if (temp > 500)
temp = temp - (1000 * (t - 1));
ifAmtLessThn2500(temp);
console.log(h + " x 100");
console.log(f + " x 500");
console.log(t + " x 1000");
}
}
}
}
checkAmt(2500);
Sorry for a dumb program, but I need help please can anyone give me a solution in typeScript code, returning the req denomination in array!!
const withdraw = (amount) => {
let hundredNotes = 0;
let fiftyNotes = 0;
let twentyNotes = 0;
while (amount >= 20) {
if (
amount >= 100 &&
((amount % 100) % 50 === 0 || (amount % 100) % 20 === 0)
) {
amount -= 100;
hundredNotes++;
} else if (
amount >= 50 &&
((amount % 50) % 100 === 0 || (amount % 50) % 20 === 0)
) {
amount -= 50;
fiftyNotes++;
} else {
amount -= 20;
twentyNotes++;
}
}
return [hundredNotes, fiftyNotes, twentyNotes];
};
console.log(withdraw(230));
console.log(withdraw(250));
amtArray = [2000, 500, 100]; // the denomination you want to find.
for (let i = 0; i < this.amtArray.length; i++) {
this.resultArray.push(Math.floor(total / this.amtArray[i]));
// Get the new total
total = total % this.amtArray[i];
}
var twothousands_notes = this.resultArray[0];
var fivehundred_notes = this.resultArray[1];
var hundred_notes = this.resultArray[2];
console.log('calculated amt : ' + '100 : ' +
hundred_notes + ' 500 : ' +
fivehundred_notes + ' 2000 : ' +
twothousands_notes);
Based on the amount you can adjust the logic.
Hope this helps.. :)
this would cover all your cases
function dispenseCase (inputAmount) {
var notes = [];
var balance = 3000;
if(inputAmount !== 0 && inputAmount % 100 == 0 && inputAmount <= balance) {
var notes2000 = Math.round(inputAmount / 2000);
var notes500 = Math.round((inputAmount - (notes2000 * 2000)) / 500 );
var notes100 = Math.round((inputAmount - ((notes2000 * 2000) + (notes500 * 500))) / 100);
notes.push(notes2000);
notes.push(notes500);
notes.push(notes100);
console.log("balance in you account = ", balance - inputAmount);
console.log(notes);
}
else if (inputAmount > balance) {
console.log("Insufficient balance in your account");
}
else if ( inputAmount % 100 != 0 || inputAmount < 100 ) {
console.log( "Invalid amount entered, amount should be multiples of 100");
}
}
dispenseCase(2600);
ATM denomination program in Javascript.
Here, It'll find the minimum number of notes of different denominations that sum the entered amount. Starting from the highest denomination note to the lowest notes.
function countCurrency(amount) {
var notes = [2000, 500, 200, 100];
var noteCounter = [0, 0, 0, 0];
for (var i = 0; i < 4; i++) {
if (amount >= notes[i]) {
noteCounter[i] = Math.floor(amount / notes[i]);
amount = amount - noteCounter[i] * notes[i];
}
}
// Print notes denomination
console.log("Denomination Count:");
for (var j = 0; j < 4; j++) {
if (noteCounter[j] !== 0) {
console.log(notes[j] + " : " + noteCounter[j]);
}
}
}
countCurrency(3300);
Here is the working example
https://codesandbox.io/s/atm-denomination-javascript-o0wb4?file=/src/index.js
this would print the number of notes in a 2000, 500, 100 order for the amount you enter
function dispenseCase (inputAmount) {
var notes = [];
if(inputAmount !== 0) {
var notes2000 = Math.round(inputAmount / 2000);
var notes500 = Math.round((inputAmount - (notes2000 * 2000)) / 500 );
var notes100 = Math.round((inputAmount - ((notes2000 * 2000) + (notes500 * 500))) / 100);
notes.push(notes2000);
notes.push(notes500);
notes.push(notes100);
console.log(notes);
}
}
dispenseCase(2600);
hope this helps
//ATM Cash Denominations //Cash Input Value Already been Provided in this method // You may use a input stream method to input a user input value
public class Denominations
{
public static void main(String args[])//throws IOException
{
int notes[]={5000,2000,1000,500,100}; //storing all the denominations in an array
int amount = 27000;
int copy=amount; //Making a copy of the amount
int totalNotes=0,count=0;
System.out.println("\nATM CASH DENOMINATIONS: \n");
for(int i=0;i<5;i++) //Since there are 5 different types of notes, hence we check for each note.
{
count=amount/notes[i]; // counting number of notes[i] notes
if(count!=0) //printing that denomination if the count is not zero
{
System.out.println(notes[i]+"\tx\t"+count+"\t= "+notes[i]*count);
}
totalNotes=totalNotes+count; //finding the total number of notes
amount=amount%notes[i]; //finding the remaining amount whose denomination is to be found
}
System.out.println("--------------------------------");
System.out.println("TOTAL\t\t\t= "+copy); //printing the total amount
System.out.println("--------------------------------");
System.out.println("Total Number of Notes\t= "+totalNotes); //printing the total number of notes
}
}
let sumToDenominate=Math.floor(Math.random() * 100);
let billsValues = [100, 50, 20, 10, 5,1];
let restAfterDenomination = [];
let billsNumber = [];
function denomination(sum, billsValues) {
printInitialValue( sumToDenominate, billsValues);
initializeArray( sumToDenominate, billsValues);
for (let i = 1; i <= billsValues.length; i++) {
if (restAfterDenomination[i - 1] > 0 || restAfterDenomination < billsNumber[i]) {
billsNumber.push(Math.floor(restAfterDenomination[i - 1] / billsValues[i]));
console.log(`bill's number of `, billsValues[i], "=>", billsNumber[i]);
restAfterDenomination.push(restAfterDenomination[i - 1] - (billsNumber[i] * billsValues[i]));
} else {
console.log(`rest is less than smallest bill or equal to 0`);
billsNumber.push(0);
// break;
}
}
}
function printInitialValue(amount, billsValue) {
console.log("Denomination sumToDenominate: ", amount);
console.log("____________");
for (const logEntry of billsValue) {
console.log(logEntry);
}
console.log("__________");
}
function initializeArray(amount, billsValues) {
billsNumber.push(Math.floor(amount / billsValues[0]));
console.log(`bill's number of`, billsValues[0], "=>", billsNumber[0]);
restAfterDenomination.push(amount - (billsNumber[0] * billsValues[0]));
denomination(sumToDenominate,billsValues);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm working through the intermediate algorithms in the FreeCodeCamp curriculum. One of them involves converting integers to roman numerals. My solution (presented below) works, however it is very much the "naive" approach, if you will. The task hints that array.splice(), array.indexOf(), and array.join() ought to be used. My implementation only uses array.join().
Edited question for precision: Will someone provide an implementation that makes use of all of the aforementioned methods?
Thanks.
My implementation:
function convertToRoman(num) {
var I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000;
var numerals = [];
var i;
if(num >= 1000){
var numMs = Math.floor(num / 1000);
for (i = 0; i < numMs; i++){
numerals.push('M');
}
num = num % 1000;
}
if(num >= 900){
numerals.push('CM');
num = num - 900;
}
if(num < 900){
if(num >= 500){
numerals.push('D');
num = num - 500;
}
if(num >= 400){
numerals.push('CD');
num = num - 400;
}
var numCs = Math.floor(num / 100);
for(i = 0; i < numCs; i++){
numerals.push('C');
}
num = num % 100;
}
if(num >= 90){
numerals.push('XC');
num = num - 90;
}
if(num < 90){
if(num >= 50){
numerals.push('L');
num = num - 50;
}
if(num >= 40){
numerals.push('XL');
num = num - 40;
}
var numXs = Math.floor(num / 10);
for(i = 0; i < numXs; i++){
numerals.push('X');
}
num = num % 10;
}
if(num == 9){
numerals.push('IX');
num = num - 9;
}
if(num < 9){
if(num >= 5){
numerals.push('V');
num = num - 5;
}
if(num >=4){
numerals.push('IV');
num = num - 4;
}
var numIs = Math.floor(num / 1);
for(i = 0; i < numIs; i++){
numerals.push('I');
}
}
var converted = numerals.join('');
return converted;
}
UPDATE: Another answer found here, but it does not use the methods I'm interested in using.
You may do as follows;
function toRoman(n){
var numerals = ["I","V","X","L","C","D","M"];
return n.toString()
.split("")
.reverse()
.reduce((p,c,i) => (c === "0" ? ""
: c < "4" ? numerals[2*i].repeat(c)
: c === "4" ? numerals[2*i] + numerals[2*i+1]
: c < "9" ? numerals[2*i+1] + numerals[2*i].repeat(c-5)
: numerals[2*i] + numerals[2*i+2]) + p,"");
}
console.log(toRoman(1453));
This is a proposal which use Array#reduce for any part of the number to convert.
function toRoman(i) {
return ('0000' + i).slice(-4).split('').map(Number).reduce(function (r, a, i) {
var value = 'MDCLXVI';
if (a === 4 || a === 9) {
r += value[i * 2];
a++;
}
if (a === 10) {
r += value[i * 2 - 2];
a -= 10;
}
if (a >= 5) {
r += value[i * 2 - 1];
a -= 5;
}
while (a) {
r += value[i * 2];
a--;
}
return r;
}, '');
}
var i;
for (i = 1; i <= 3000; i++) {
document.getElementById('tt').innerHTML += i + ' ' + toRoman(i) + `\n`;
}
<pre id="tt"></pre>
Say you have the number var n = 1,000,000;
I want to check:
n >= 1e3
n >= 1e4
n >= 1e5
n >= 1e6
Doing it exactly as it looks above will cause the statement to return true on the first valid expression, obviously. Which means that it will say n is greater than 1e3 and return the results from there.
How can I get it to instead 'cascade' through the expressions until it hits a false, then use the last statement that was true, without having to go:
if( n >= 1e3 && n >= 1e4 && n >= 1e5 && n >= 1e6 ) {...
You should check the number from the biggest to the smalest:
var n = 1000000;
var r = document.getElementById("result");
if (n >= 1e6) r.innerHTML = "n >= 1e6";
else if (n >= 1e5) r.innerHTML ="n >= 1e5";
else if (n >= 1e4) r.innerHTML ="n >= 1e4";
else if (n >= 1e3) r.innerHTML = "n >= 1e3";
<div id="result"></div>
If you need to have all the diffent sentences, you can do:
var r = document.getElementById("result");
var n = 1000000;
var str = "";
if (n >= 1e6) str += "n >= 1e6 ";
if (n >= 1e5) str += "n >= 1e5 ";
if (n >= 1e4) str += "n >= 1e4 ";
if (n >= 1e3) str += "n >= 1e3 ";
r.innerHTML = str;
<div id="result"></div>
To have something more maintainable and extendable :
var n = 1000000;
var r = document.getElementById("result");
check(n, [1000, 1e4, 1e5, 1e6]);
function check(nb, limits) {
limits.sort(function(a, b){return b-a});
var limitsLength = limits.length;
for (var i =0;i<limitsLength;i++) {
if (nb >= limits[i]) r.innerHTML += "n >= 1e" + Math.log10(limits[i]) + " ";
}
}
<div id="result"></div>
No need for branching.
function yours() {
if (n < 1) return 'n is less than 1e0';
return 'n is greater than 1e' + Math.log10(n);
}
If you must branch (for example if you are actually calculating something more complex than a simple logarithm), add a new function to avoid the "cascading" you mention. The return statements will prevent cascading. The new function defines how much stuff gets skipped.
function yours() {
println(figure(n));
}
function figure(n) {
if (n > 10000) return 'n is greater than 1e4';
if (n > 1000) return 'n is greater than 1e3';
if (n > 100) return 'n is greater than 1e2';
if (n > 10) return 'n is greater than 1e1';
if (n > 1) return 'n is greater than 1e0';
}
I'm using println here as a substitute for whatever you want to do with the result.
How do I format a negative number to be like this?
-5000 -> -5 k
-1000000 -> -1 M
-2700000000 -> -2.7 B
Here's a function you can use:
function format_number(num) {
var identifiers = ['k', 'M', 'B'];
var identifierLengthMinusOne = identifiers.length - 1;
var identifierOffset = -1;
var isNegative = (num < 0);
num = Math.abs(num);
while (num >= 1000 && identifierOffset < identifierLengthMinusOne) {
num /= 1000;
identifierOffset++;
}
return (isNegative ? num * -1 : num) + (identifierOffset > -1 ? ' ' + identifiers[identifierOffset] : '');
}
> format_number(-500)
"-500"
> format_number(-50000)
"-50 k"
> format_number(-50000000)
"-50 M"
> format_number(-50000000000)
"-50 B"
> format_number(-50000000000000)
"-50000 B"
check this:
function intToString (value) {
var suffixes = ["", "k", "m", "b","t"];
var suffixNum = Math.floor((""+value).length/3);
var shortValue = parseFloat((suffixNum != 0 ? (value / Math.pow(1000,suffixNum)) : value).toPrecision(2));
if (shortValue % 1 != 0) shortNum = shortValue.toFixed(1);
return shortValue+suffixes[suffixNum];
}
usage:
intToString (-5000)