I am new to JS and trying to remove the full stop from the returned number, I've managed to work out removing the thousand separator but not sure how to add to also remove the full stop. Anyone have any ideas?
JS
var total = parseFloat(a) + parseFloat(b);
total = parseFloat(Math.round(total * 100) / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
total = total.replace(/\,/g,'');
var newTotal = Shopify.formatMoney(total, '{{ shop.money_format }}');
Currently returns:
5977.00
But think I need to return it like
597700
So that the Shopify(formatMoney) function re-builds it.
add the line:
total = total.replace(/\./g,'');
Or, remove both the comma and the period at once with:
total = total.replace(/\.|\,/g,'');
Look up 'regular expressions' for more info on how to create searches for specific patterns in text.
You can use .split & .join like so:
total = total.split('.').join("");
Refer to this page here: removing dot symbol from a string
You can also use
Math.round(total)
or
parseInt(total);
Related
World!
I'm trying to create a program in Javascript that takes the log of a number typed into an HTML input. Unfortunately i've encountered a problem where it wont accept the string with the .replace().
Its Function:
I.E: When log(10) is calculated, the function should first remove the first 4 char's "log(" next remove the last parenthesis ")" and then take the log of the no. between.
HTML includes style elements, button and input form and an output < DIV >.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
//TESTING CODE
/*
if (inputString.value.startsWith("log(").endsWith(")"))
{
console.log(output.innerHTML = inputString.value.substring(4, 20).replace(")", ""));
}
else
{
output.innerHTML = "false";
}
*/
//Math.log() calc *****DOESNT WORK*****
if (inputString.value.startsWith("log(").endsWith(")"))
{
output.innerHTML = Math.log(inputString.value.replace(")", "").substring(4, 20));
}
else
{
output.innerHTML = inputString.value;
}
event.preventDefault();
}
If someone can give me an effective solution that would be much appreciated.
Thanks,
Syntax
Since Math.log() accepts only number values and you're trying to pass a string to it, you should first parse this value into a float number and then pass it to the log function:
let val = parseFloat(inputString.value.replace(")", "").substring(4, 20));
output.innerHTML = Math.log(val);
I'm guessing I got downvoted for being lazy, so here is the quick info. Gonras got it right relating to what you want to extract, but he forgot to check that what's being input is actually a log.
That's where the regex below comes in handy! I'm matching the field to:
^ start of word, since we want to match the entire field.
log(
([-.\d])) any consecutive sequence () of numbers (\d), -, and '.', represented by the []. The \(...\) makes sure to save this inner part for later.
$ is end of word, see 1.
res will be null if there is no match. Otherwise, res[0] is the entire match (so the entire input field) and res[1] is the first 'capture group', at point 3 - which is presumably the number.
This of course fails for multiple "-" inside, or "." etc... so think it over.
//Function
function calculate()
{
var inputString = document.getElementById("inpstr");
var output = document.getElementById("output");
var res = /^log\(([-.\d]*)\)$/.exec(inputString.value);
if (res)
output.innerHTML = Math.log(res[1]);
else
output.innerHTML = res;
}
document.getElementById("output").innerHTML='start';
calculate()
<div id='output'></div>
<input id='inpstr' value='log(2.71828)'></input>
If I wanted to fix your if to supplement Gonras's solution:
if (inputString.value.startsWith("log(") && inputString.value.endsWith(")"))
Yours fails since startsWith() returns a boolean, which obviously doesn't have a endsWith function.
I am trying to develop the addition program using column addition in javascript, For e.g: 53,22 , we add numbers from the right 3+2 and 5+2 finally results in 75, the main problem is with large numbers i am trying to develop a program which can implement addition of large numbers.so that i don't get gibberish like 1.26E+9, when adding large numbers. i tried doing it by defining the code like below
function add(a,b)
{
return (Number(a) + Number(b)).toString();
}
console.log(add('58685486858601586', '8695758685'));
i am trying to get the added number without getting the gibberish like 5.8685496e+16
You can add them digit by digit.
function sumStrings(a, b) { // sum for any length
function carry(value, index) { // cash & carry
if (!value) { // no value no fun
return; // leave shop
}
this[index] = (this[index] || 0) + value; // add value
if (this[index] > 9) { // carry necessary?
carry.bind(this)(this[index] / 10 | 0, index + 1); // better know this & go on
this[index] %= 10; // remind me later
}
}
var array1 = a.split('').map(Number).reverse(), // split stuff and reverse
array2 = b.split('').map(Number).reverse(); // here as well
array1.forEach(carry, array2); // loop baby, shop every item
return array2.reverse().join(''); // return right ordered sum
}
document.write(sumStrings('58685486858601586', '8695758685') + '<br>');
document.write(sumStrings('999', '9') + '<br>');
document.write(sumStrings('9', '999') + '<br>');
document.write(sumStrings('1', '9999999999999999999999999999999999999999999999999999') + '<br>');
I would keep all values as numbers until done with all the calculations. When ready to display just format the numbers in any way you want. For example you could use toLocaleString.
There are several libraries for that
A good rule of thumb is to make sure you do research for libraries before you actually go ahead and create you're own proprietary implementation of it. Found three different libraries that all solve your issue
bignumber.js
decimal.js
big.js
Example
This is how to use all three of the libraries, BigNumber coming from the bignumber.js library, Decimal from decimal.js and Big from big.js
var bn1 = new BigNumber('58685486858601586');
var bn2 = new BigNumber('8695758685');
console.log(bn1.plus(bn2).toString());
bn1 = new Decimal('58685486858601586');
bn2 = new Decimal('8695758685');
console.log(bn1.plus(bn2).toString());
bn1 = new Big('58685486858601586');
bn2 = new Big('8695758685');
console.log(bn1.plus(bn2).toString());
The console's output is :
58685495554360271
58685495554360271
58685495554360271
im trying to find if there is any javascript to format a string for display, so for exam "1234"- or any string over length 2- would become 12** i know there is a replace method but not sure how this would work. any suggestions welcome. thanks much
Assuming you want to mask the equivalent number of characters you can replicate * length - 2 times & append the 1st 2 characters of the original string;
var str = "123456";
var numCharsToKeep = 2;
if (str.length > numCharsToKeep)
str = str.substr(0, numCharsToKeep) + Array(str.length - numCharsToKeep + 1).join("*")
== "12******"
I have a function with info that grabs hours, rates, and then tax deduction and then spits it out. It works fine
var newtax= new Number(dep[i]);
taxrate = newtax*100;
var h=eval(document.paycheck.hours.value);
var r=eval(document.paycheck.payrate.value);
document.paycheck.feedback.value= taxrate + txt;
var total= r*(1-newtax)*h ;
total=total.toFixed(2);
document.paycheck.feedback3.value= ("$ "+ total);
I have to put where it takes the total and puts it in a function to put it only two decimals. It works this way and only does two decimals but i need the decimal conversion in a function. can anyone shed some like .
This is where i cut it to two decimals and i am unable to put in function and then send it back to the feedback3.value.
total=total.toFixed(2);
document.paycheck.feedback3.value= ("$ "+ total);
If you're asking how to write a function that takes a number and formats it as a dollar value with two decimals (as a string) then this would work:
function formatMoney(num) {
return "$ " + num.toFixed(2);
}
// which you could use like this:
document.paycheck.feedback3.value= formatMoney(total);
// though you don't need the total variable (unless you use it elsewhere)
// because the following will also work:
document.paycheck.feedback3.value = formatMoney( r*(1-newtax)*h );
By the way, you don't need eval to get the values from your fields. Just say:
var h = document.paycheck.hours.value;
var r = document.paycheck.payrate.value;
I am trying to get sum of rows of my table:
td1 val = $5,000.00; td2 val = $3000.00;
And I am using the following code:
var totalnum = 0;
$('.num').each(function(){
totalnum+= parseFloat($(this).html());
});
$('.total_num').html(totalnum);
This code works perfect if I remove money formatting from the number, otherwise it gives NaN as a result even if I am using parseFloat.
What am I missing?
Try:
var totalnum = 0;
$('.num').each(function(){
totalnum+= parseFloat($(this).html().substring(1).replace(',',''));
});
$('.total_num').html('$' + totalnum);
This will remove the $ (or whatever currency symbol) from the beginning and all commas before doing the parseFloat and put it back for the total.
Alternatively you could use the jQuery FormatCurrency plugin and do this:
totalnum+= $(this).asNumber();
If you add $ to the value, it is no longer an integer, and can no longer be calculated with.
Trying to make the formatted value back into a number is a bad idea. You would have to cater for different currency symbols, different formattings (e.g. 1.000,00) and so on.
The very best way would be to store the original numeric value in a separate attribute. If using HTML 5, you could use jQuery's data() for it:
<td class="num" data-value="1.25">$1.25</td>
....
var totalnum = 0;
$('.num').each(function(){
totalnum+= parseFloat($(this).data("value"));
});
$('.total_num').html(totalnum);
this way, you separate the formatted result from the numeric value, which saves a lot of trouble.
Try removing $ and any other character not part of the float type:
var totalnum = 0;
$('.num').each(function(){
var num = ($(this).html()).replace(/[^0-9\.]+/g, "");
totalnum+= parseFloat(num);
});
$('.total_num').html(totalnum);
Edit: updated replace to remove all non-numerical characters (except periods) as per this answer.