Number formatting remove numbers after dot add comma at thousands - javascript

Currently output 1844.6304
desired output - comma thousands trim after dot ( no rounding )
1,844
I was looking some time on forums and can't find a solution to solve both cases.

Try this:
function intWithCommas(x) {
return Math.floor(x).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Example:
> intWithCommas(1844.6304)
'1,844'

Its even simpler like this
var n = 1844.6304,
s = Math.floor(n).toLocaleString();
console.log(s); //"1,844"
alert(s);

Try this:
function toCommaInteger(number){
var result = "" + ~~number;
var length = result.length;
var limit = result[0] === "-" ? 1 : 0;
for(var i = length-3; i > limit; i-=3 ){
result = result.substring(0,i) + "," + result.substring(i,length);
length++;
}
return result;
}
toCommaInteger(123589.85315) => 123,589
toCommaInteger(-1289.15315) => -1,289
toCommaInteger(5) => 5

Related

Javascript Regex Custom Replace

How do I get the following conversion using Regex?
Content(input data structure):
a-test
b-123
c-qweq
d-gdfgd
e-312
Conversion:
1-test
2-123
3-qweq
4-gdfgd
Final-312
var index = 1;
function c_replace() {
if(index == 5) { return "Final"; }
return index++;
}
there you go :D
// i assume you have a string input that contains linebreaks due to your question format
const input = `a-test
b-123
c-qweq
d-gdfgd
e-312`.trim(); // removing whitespace in front or behind the input data.
//splitting the lines on whitespace using \s+
const output = input.split(/\s+/).map((s, i, a) => {
// this will map your pattern asd-foooasdasd
const data = s.match(/^[a-z]+-(.+)$/);
// you may want to tweak this. right now it will simply throw an error.
if (!data) throw new Error(`${s} at position ${i} is a malformed input`);
// figure out if we are in the final iteration
const final = i == a.length -1;
// the actual output data
return `${final ? "Final" : (i + 1)}-${data[1]}`;
// and of course join the array into a linebreak separated list similar to your input.
}).join("\n");
console.log(output);
Test
var index=1;
var text=`a-test
b-123
c-qweq
d-gdfgd
e-312`;
function c_replace() {
if(index == 5) { return "Final-"; }
return index++ +'-';
}
console.log(text.replace(/.-/g,c_replace));
var input = [
'a-test',
'b-123',
'c-qweq',
'd-gdfgd',
'e-312'
];
var output = input.map((e, i) => ++i + e.slice(1));
output[output.length - 1] = 'Final' + output[output.length - 1].slice(1);
console.log(output);

separating numbers into sum of positional digits in javascript

I'm working with freecodecamp studies and need to find a way to turn a number into sum of positional digits like [1234] to [1000,200,30,4].
Code looks like this:
for(var i=0;i<newArr.length;i++){
var order = newArr.length-1 - i;
newArr.splice(i,1,newArr[i]*1e(order));
}
Here newArr will be 1234.
Node gives error: invalid token 1e(order).
Need some advice how to make it right.
I think you can use the below logic
var n = 123456;
n=n.toString();
var arr = n.split("");
var b = arr.map(function(x,i) {
return x * Math.pow(10, (arr.length-i-1));;
});
console.log(b);
var a = 1234
b = []
while(a>0){
b.unshift(a%10 * (10 ** b.length))
a = parseInt(a/10)
}
console.log(b)
Number.prototype.padRight = function (n,str) {
return (this < 0 ? '-' : '') + (Math.abs(this)+ Array(n-String(Math.abs(this)).length+1).join(str||'0'));
}
var digits = "1234"
var tempCounter= digits.length;
var result=[];
for(var i=0;i<digits.length;i++,tempCounter--){
result.push(parseInt(digits[i]).padRight(tempCounter))
}
console.log(result);

How do I match the numbers sequence rising?

I have a string contains just numbers. Something like this:
var numb = "5136789431235";
And I'm trying to match ascending numbers which are two or more digits. In string above I want this output:
var numb = "5136789431235";
// ^^^^ ^^^
Actually I can match a number which has two or more digits: /[0-9]{2,}/g, But I don't know how can I detect being ascending?
To match consecutive numbers like 123:
(?:(?=01|12|23|34|45|56|67|78|89)\d)+\d
RegEx Demo
To match nonconsecutive numbers like 137:
(?:(?=0[1-9]|1[2-9]|2[3-9]|3[4-9]|4[5-9]|5[6-9]|6[7-9]|7[8-9]|89)\d)+\d
RegEx Demo
Here is an example:
var numb = "5136789431235";
/* The output of consecutive version: 6789,123
The output of nonconsecutive version: 136789,1234
*/
You could do this by simply testing for
01|12|23|34|45|56|67|78|89
Regards
You just need to loop through each number and check next one. Then add that pair of values to a result variable:
var numb = "5136789431235";
var res = [];
for (var i = 0, len = numb.length; i < len-1; i++) {
if (numb[i] < numb[i+1]) res.push(new Array(numb[i],numb[i+1]))
}
res.forEach(function(k){console.log(k)});
Here is fiddle
Try this to match consecutive numbers
var matches = [""]; numb.split("").forEach(function(val){
var lastNum = 0;
if ( matches[matches.length-1].length > 0 )
{
lastNum = parseInt(matches[matches.length-1].slice(-1),10);
}
var currentNum = parseInt(val,10);
if ( currentNum == lastNum + 1 )
{
matches[matches.length-1] += String(currentNum);
}
else
{
if ( matches[matches.length-1].length > 1 )
{
matches.push(String(currentNum))
}
else
{ matches[matches.length-1] = String(currentNum);
}
}
});
matches = matches.filter(function(val){ return val.length > 1 }) //outputs ["6789", "123"]
DEMO
var numb = "5136789431235";
var matches = [""]; numb.split("").forEach(function(val){
var lastNum = 0;
if ( matches[matches.length-1].length > 0 )
{
lastNum = parseInt(matches[matches.length-1].slice(-1),10);
}
var currentNum = parseInt(val,10);
if ( currentNum == lastNum + 1 )
{
matches[matches.length-1] += String(currentNum);
}
else
{
if ( matches[matches.length-1].length > 1 )
{
matches.push(String(currentNum))
}
else
{ matches[matches.length-1] = String(currentNum);
}
}
});
matches = matches.filter(function(val){ return val.length > 1 }) //outputs ["6789", "123"]
document.body.innerHTML += JSON.stringify(matches,0,4);
Do you have to use Regex?
Not sure if the most efficient, but since they're always going to be numbers, could you split them up into an array of numbers, and then do an algorithm on that to sort through?
So like
var str = "123456";
var res = str.split("");
// res would equal 1,2,3,4,5,6
// Here do matching algorithm
Not sure if this is a bad way of doing it, just another option to think about
I've did something different on a fork from jquery.pwstrength.bootstrap plugin, using substring method.
https://github.com/andredurao/jquery.pwstrength.bootstrap/commit/614ddf156c2edd974da60a70d4945a1e05ff9d8d
I've created a string containing the sequence ("123456789") and scanned the sequence on a sliding window of size 3.
On each scan iteration I check for a substring of the window on the string:
var numb = "5136789431235";
//check for substring on 1st window => "123""
"5136789431235"
ˆˆˆ

Adding comma separators into calculation result

How can I have comma separators displayed in the calculation results?
(123456789 to show as 123,456,789)
function calculate(){
a=Number(document.calculator.number1.value);
b=Number(document.calculator.number2.value);
A1=a*2000
document.calculator.totalA1.value=A1;
A2=a*b*240
document.calculator.totalA2.value=A2;
A3=a*8*240
document.calculator.totalA3.value=A3;
A4=a*960*5
document.calculator.totalA4.value=A4;
A5=a*3600*5
document.calculator.totalA5.value=A5;
A6=a*3000
document.calculator.totalA6.value=A6;
A7=A1+A2+A3+A4+A5+A6
document.calculator.totalA7.value=A7;
A8=a*120000
document.calculator.totalA8.value=A8;
A9=A8-A7
document.calculator.totalA9.value=A9;
}
I've seen many suggestions but don't know where to insert the script.
Thanks!
You could try something like this using RegExp
$("#button").click(function(){
var a = 100;
var A1=(a*2000);
alert(String(A1).replace(/(\d{3})(?!$)/g, "$1,"));
})
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<button type="button" id="button">Calculate </button>
Here you go: https://jsfiddle.net/odewuqun/3/
function addPunctuation(number){
var array = number.toString().split("");
var output = "";
var first = true;
for(var i = array.length-1; i >= 0; i--){
if((array.length-i-1) % 3 === 0){
if(first){
first = false;
}else{
output = "," + output;
}
}
output = array[i] + output;
}
return output;
}
Short explanation:
Convert the number into a String.
Split that String into an array.
Iterate over that array from the end and make a new String where you add a , between every 3 chars.
That is archieved by index % 3 === 0. (% is the mathematic modulo operator for whole number division with rest)

How do I convert an integer to decimal in JavaScript?

I have a number in JavaScript that I'd like to convert to a money format:
556633 -> £5566.33
How do I do this in JavaScript?
Try this:
var num = 10;
var result = num.toFixed(2); // result will equal string "10.00"
This works:
var currencyString = "£" + (amount/100).toFixed(2);
Try
"£"+556633/100
This script making only integer to decimal.
Seperate the thousands
onclick='alert(MakeDecimal(123456789));'
function MakeDecimal(Number) {
Number = Number + "" // Convert Number to string if not
Number = Number.split('').reverse().join(''); //Reverse string
var Result = "";
for (i = 0; i <= Number.length; i += 3) {
Result = Result + Number.substring(i, i + 3) + ".";
}
Result = Result.split('').reverse().join(''); //Reverse again
if (!isFinite(Result.substring(0, 1))) Result = Result.substring(1, Result.length); // Remove first dot, if have.
if (!isFinite(Result.substring(0, 1))) Result = Result.substring(1, Result.length); // Remove first dot, if have.
return Result;
}
Using template literals you can achieve this:
const num = 556633;
const formattedNum = `${num/100}.00`;
console.log(formattedNum);

Categories