Javascript mask - javascript

How do you format a number to show 2 decimals in JavaScript?
Something along the lines of:
format(x,"9,999.99");

You should use this :
x.toFixed(2);
or if you want to be sure it will work :
parseFloat(x).toFixed(2);

var num = 3.14159;
var fixed = num.toFixed(2);
If you want the commas depending on the locale:
var localed = num.toLocaleString();
Combining both crudely:
var num = 3.14159;
var fixed = num.toFixed(2);
var fixednum = parseFloat(fixed);
var localedFixed = fixednum.toLocaleString();

Use .toFixed(2):
http://www.devguru.com/technologies/javascript/17443.asp
Note this will round your number:
var i = 23.778899;
alert(i.toFixed(2));
gives you
23.78

I'm not sure if you are trying to do this to input or just for displaying text on the page. You can use the masked input plugin for jQuery if you are trying to format input.
http://digitalbush.com/projects/masked-input-plugin/

Related

Javascript Number formating winthout numbers after comma

I am trying this script to calculate and print the result in a form input readonly. While this works fine i need the numbers to be shown like this: 2.000.000 instead of 2.000.000.00. I need those 2 zeros at the end gone. I googled it but all I find are solutions with the comma intact. As this script is very basic and simple i hope that for my problem there is a very simple and basic solution.
<script>
getPrice = function() {
var numVal1 = Number(document.getElementById("price").value);
var numVal2 = Number(document.getElementById("discount").value) ;
var totalValue = numVal1 * numVal2
document.getElementById("total").value = totalValue.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&.');
}
</script>
Have you tried this :
totalValue.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&.').slice(0, -3)

Calculating 2 values from fields but it's not working properly

I am calculating 2 fields on a form with values but it seems in some cases it's not working. Here's my javascript. I am adding $oneTimeCostField and $recurringTotalCostField to get the value into the $totalRetailAmountField. Here's the result I am getting when I add say 1,555.00 + 566.00 = the value is 567.00 (?). Any idea what I'm doing wrong? In some cases it works correctly when the values are lower. Thanks, just stumped
var $recurringCostField = $('#am_attribute_campaign_addon_monthly_cost_value');
var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_oie_string_total_monthly_cost_value');
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
function calcVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseFloat(num1) + parseFloat(num2);
if (!isNaN(result)) {
$totalRetailAmountField.val(result.toFixed(2));
}
}
calcVal();
$oneTimeCostField.on("keydown keyup", function() {
calcVal();
});
$recurringTotalCostField.on("keydown keyup", function() {
calcVal();
});
You need to remove the commas before parsing:
var result = parseFloat(num1.replace(/,/g, '')) + parseFloat(num2.replace(/,/g, ''));
similiar question on this link
Remove commas from the string using JavaScript
That is because parseFloat() converts the string "1,555.00" to the number 1.
To convert it to a proper floating point number, it needs to include a single dot only.
console.log(parseFloat("1.555"));

Type Conversion Issue(?): How to grab html <span> tag's value and perform math on it?

How would I use javascript to take 30% off of the price and then append the discounted price under the old price? I'm getting tripped up on this.
Someone advised that I need to remove the $ some other way...?
HTML
<span class="price">$59.00</span>
JavaScript
var priceOne = parseInt(document.querySelector(".price").innerHTML);
var priceTwo = "$" + priceOne * .70;
document.querySelector(".price").innerHTML = priceTwo;
All tips or advice or solutions is appreciated!
JavaScript isn't able to parse strings to numbers if they have a string in it for whatever reason.
var price = document.getElementsByClassName('price')[0];
price.innerHTML += '<br>$' + (parseFloat(price.innerHTML.replace('$', ''))*0.7).toFixed(2);
<span class="price">$59.00</span>
You can use regular expressions
var priceOne = document.querySelector(".price").innerHTML;
// Use regular expression to strip out all non-numbers
var re = /\.\d+|\d\/\d|\d/g
var result = priceOne.match(re).join('');
//if in the united states, use this, else look on MDN for the correct formatting
document.querySelector(".price").innerHTML = (result*.7).toLocaleString("en-US",{style:"currency",currency:'USD'})
let oriprice = document.getElementById('price').innerHTML;
let priceOne = parseFloat(oriprice.substring(1,oriprice.length));
var priceTwo = "$" + (priceOne * .70).toFixed(2);
console.log(priceTwo)
<span id="price">$59.00 </span>
The problem is that your priceOne was NaN after parsed. Try to use subString to remove the first $ sign, and since it's a decimal amount, instead of using parseInt, use parseFloat and after calculating the 70% of it, apply toFixed on it

How to convert danish currency to digit

I have currency like 3.477,60 kr and i want to use this currenty in js code to add extra price calculation logic. and i have used below code to format it but it give NaN in alert.
var currency = "3.477,60 kr";
var number = Number(currency.replace(/(\..*)\./g,'$1'));
alert(number);
i want output like 3477.60
can any one please guide me on this.
Here you go
var currency = "3.477,60 kr";
var number = currency.replace(/\./g, '').replace(/\,/g, '.').replace(/ kr/g,'');
alert(number);
Try this-
var currency = "3.477,60 kr";
var value = currency.replace(/\./g, '').replace(/\,/g, '.').split(' ')[0]
console.log(value);

Adding User input without rounding (Google Apps Script)

I am adding a users input in to UI as they add numbers and returning the results. The input is currency so I need to carry it out two decimals and not round.
Here is an example of my code:
function ceiling2(number) {
var ceiling2;
return ceiling2 = Math.ceil(number*100)/100;
}
//Totals
function lD23Total (e){
var app = UiApp.getActiveApplication();
var tB1v = parseInt(e.parameter.TextBox1);
var tB9v = parseInt(e.parameter.TextBox9);
var tB17v = parseInt(e.parameter.TextBox17);
var tB25v = parseInt(e.parameter.TextBox25);
var tB33v = parseInt(e.parameter.TextBox33);
var tB41v = parseInt(e.parameter.TextBox41);
var tB49v = parseInt(e.parameter.TextBox49);
var lD23 = app.getElementById("LabelD23").setStyleAttribute('fontWeight','bold');
var lD23T = tB1v + tB9v + tB17v + tB25v + tB33v + tB41v + tB49v;
lD23.setText("$ " + ceiling2(lD23T));
var app = UiApp.getActiveApplication();
app.close();
return app;
}
Currently it returns a rounded number.
I appreciate an suggestions you may offer!
Jon
The function parseInt() will convert the value to an integer, dropping the values after the decimal. Use parseFloat() instead.
I think your function is just fine...
if you remove the parseInt() and replace it either with parseFloat()as suggested by Eric or by Number() it should work...
if not then the problem might come from the way numbers are written:
If you used 26,4567 but you should use 26.4567 with a dot as separator in place of a comma.
Could you try and keep us informed ?
regards,
Serge
Or you can use this before sending to your function:
var newnumber=Number(number.toString().replace(",","."));// convert to string, replace comma with dot and set as number again.
and your function will work in both cases

Categories

Resources