javascript convert currency to thousands - javascript

I have a decimal number*(28045.124578)* and i want it to be converted so that it will show in thousand currency format($28.0K) using javascript.
I am using this script tp convert but this doesn't help
function kFormatter(num) {
num = num.toString().replace(/\$|\,/g, '');
if (isNaN(num))
{
num = "0";
}
num = Math.floor(num * 100 + 0.50000000001);
cents = num % 10;
num = Math.floor(num / 100000).toString();
//console.log('num=', num/1000);
if (cents < 10)
{
cents = "0" + cents;
}
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
{
num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
}
return num + '.' + cents;
}
but this doesn't help. Please suggest.

You can use round to get the nearest whole number.
function kformatter(num){
var newvalue = Math.round(num/100);
return newvalue?(newvalue/10)+"K":num;
}

Related

Count the number of occurrences of 7 in a number given by the user

while (a) {
b.push(a % 10);
a = Math.floor(a / 10);
if (b == 7) {
n = n + 1;
}
console.log("<br><br>number of 7's:" + n);
}
This is what I have come up with. The output is one of the numbers has seven; if not, then zero. I want the program to count the number of times seven appears in a number.
You can convert the number to a string, and then count how many times a character = 7:
let n = 7326577
let cnt = 0;
let strN = '' + n;
for(let c of strN)
if(c == '7')
cnt ++
console.log('Number of 7\'s in number: ' + cnt)
Following you approach you need to store the last digit to a different variable and use that for checking if it is a 7
var a = 709728457;
var b = [];
var n = 0;
while (a) {
const lastDigit = a % 10;
b.push(lastDigit); // if you still need to store all digits
a = Math.floor(a / 10);
if (lastDigit == 7) {
n = n + 1;
}
}
console.log("number of 7's:" + n);
var a = 7686774737
var no = String(a).split('').filter(e=>e==7).length;
console.log(no)

Sorting an integer without using string methods and without using arrays

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/

Format numbers in comma separated value

I am using javascript to format the number with commas , it was working very fine.
But now the problem is if a value is comming in negative for example : -792004
It is returning the output like : -,792,004 that is comma is in the start.
How can I modify this method ?
Here is my code :
function Comma(number) {
number = '' + number;
if (number.length > 3) {
var mod = number.length % 3;
var output = (mod > 0 ? (number.substring(0, mod)) : '');
for (i = 0; i < Math.floor(number.length / 3); i++) {
if ((mod == 0) && (i == 0))
output += number.substring(mod + 3 * i, mod + 3 * i + 3);
else
output += ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
}
return (output);
} else return number;
}
The simplest way I know which will helps you is toLocaleString() method on number:
var x = 10033001;
var y = -10033001;
console.log(x.toLocaleString(), y.toLocaleString());
But for correction of your code, you can remove number sign with Math.abs and add it after with Math.sign.
var sign = Math.sign(number);
number = Math.abs(number);
// Do the conversion
return (sign < 0) ? ("-" + output) : output;
Try this:
const comma = function(number) {
const prefix = number < 0 ? '-' : ''
number = String(Math.abs(number))
if (number.length > 3) {
const mod = number.length % 3
let output = (mod > 0 ? (number.substring(0,mod)) : '')
for (let i = 0; i < Math.floor(number.length / 3); i++) {
if (mod === 0 && i === 0)
output += number.substring(mod+ 3 * i, mod + 3 * i + 3)
else
output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
}
return prefix + output
} else {
return prefix + number
}
}
If the number is negative, it assigns - to prefix. Then it changes number to its absolute value (Math.abs(number)). In the end it returns value with prefix.

parseInt value from input and use as a check for the sum of last value with Javascript

Trying to track the numbers in an input value and use these as a checkdigit for the last number. Basically, grab the first nine digits of the input, run some simple math and then add those numbers together. Take that total, divide by two then use the remainder as the check digit.
Thus far unsuccessful so if anyone has a good idea of where I am going wrong would gladly appreciate it. I put a fiddle up here: Das Fiddle
window.onkeyup = keyup;
var inputTextValue;
function keyup(e) {
inputTextValue = e.target.value;
$('#numberValue').text(inputTextValue);
// must be 10 characters long
if (inputTextValue.length !== 10) {
return false;
}
// run the checksum
var valid = false;
try {
var sum = (parseInt(inputTextValue[0], 10) * 2) +
(parseInt(inputTextValue[1], 10) * 3) +
(parseInt(inputTextValue[2], 10) * 4) +
(parseInt(inputTextValue[3], 10) * 2) +
(parseInt(inputTextValue[4], 10) * 3) +
(parseInt(inputTextValue[5], 10) * 4) +
(parseInt(inputTextValue[6], 10) * 2) +
(parseInt(inputTextValue[7], 10) * 3) +
(parseInt(inputTextValue[8], 10) * 4);
var checkNumber = 0;
if ((sum % 10) > 0) {
checkNumber = (sum % 10).toFixed(-1);
}
if (inputTextValue[9] === ("" + checkNumber)) {
valid = true;
alert(checkNumber)
}
} catch (e) {
valid = false;
}
return valid;
}
You should be using :
checkNumber = (sum % 10).toFixed(0);
toFixed(-1) will return 0.
Fiddle here

How can I have the value round up in javascript?

I have a code that is inserting the total value into a textbox, however, the math that is performed does not round the number. Based on the code below how can I make this happen?
function calculate(){
var mrc = document.getElementById('box1');
var days = document.getElementById('box2');
var total = document.getElementById('box3');
var reason = document.getElementById('box4');
var approver = document.getElementById('box5');
var approvalreason = document.getElementById('box6');
var custname = document.getElementById('box7');
var caseid = document.getElementById('box8');
var intermitent = document.getElementById('rb1');
var outage = document.getElementById('rb2');
if (outage.checked === true) {
if (days.value * 5 > mrc.value){
total.value = (mrc.value / 30) * days.value;
} else if (days.value > 14) {
total.value = (mrc.value / 30) * days.value;
} else {
total.value = days.value * 5;
}
} else if (intermitent.checked === true){
if (days.value * 3 > mrc.value)
{
total.value = (mrc.value / 30) * days.value;
} else if (days.value > 14) {
total.value = (mrc.value / 30) * days.value;
} else {
total.value = days.value * 3;
}
}
}
Two things:
You're playing with fire by using implicit type conversion. element.value returns a string, not a number, so you should be using parseInt() or parseFloat() to convert your values to numbers. For instance, if your input has value 3, and you do element.value + 2, the result is 32.
Second, to your question, Math.ceil() rounds a float up to the near integer.
Use round() method to rounds a number to the nearest integer.
Example:
var a = Math.round(8.70);
Answer a = 9;
Try the following code:
function toFixed(value, precision) {
var precision = precision || 0,
power = Math.pow(10, precision),
absValue = Math.abs(Math.round(value * power)),
result = (value < 0 ? '-' : '') + String(Math.floor(absValue / power));
if (precision > 0) {
var fraction = String(absValue % power),
padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
result += '.' + padding + fraction;
}
return result;
}
alert(toFixed(1.0000000,3));
Following is the fiddle link:
Demo

Categories