javascript format price - javascript

I wish to format a variable to a price format where if it is for example $90 then leave out the decimal which it already does anyway. But if the value is $44.5 then I want to format it as $44.50. I can do it in php not javascript.
PHP example:
number_format($price, !($price == (int)$price) * 2);
The code I want to format:
$(showdiv+' .calc_price span').html(sum_price);

var price = 44.5;
var dplaces = price == parseInt(price, 10) ? 0 : 2;
price = '$' + price.toFixed(dplaces);

PHPJS has that code for you: http://phpjs.org/functions/money_format:876
Also provided by #Daok How can I format numbers as money in JavaScript?

Try this
function priceFormatter(price)
{
//Checks if price is an integer
if(price == parseInt(price))
{
return "$" + price;
}
//Checks if price has only 1 decimal
else if(Math.round(price*10)/10 == price)
{
return "$" + price + "0";
}
//Covers other cases
else
{
return "$" + Math.round(price*100)/100;
}
}

Related

Javascript restrict input once 2 decimal places have been reached

I currently have a number input script that behaves similar to a calculator with the way numbers are displayed, but I want to stop the adding of additional numbers to the series after two numbers past the decimal point.
Here is what I have so far, though the limiting doesn't occur correctly.
It should work like this:
1.25 - Allowed
12.5 - Allowed
125.5 - Allowed
125.55 - Allowed
123.555 - Not Allowed
rText = document.getElementById("resultText");
function selectNumber(num) {
if (!rText.value || rText.value == "0") {
rText.value = num;
}
else {
this part works...
rText.value += num;
}
}
}
but this part doesn't work... Any ideas???
if (rText.value.length - (rText.value.indexOf(".") + 1) > 2) {
return false;
} else {
rText.value += num;
}
}
}
var validate = function(e) {
var t = e.value;
e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
}
<input type="text" id="resultText" oninput="validate(this)" />
Save the previous value in some data attribute and if it exceeds 2 decimal places then restore the previous value
The 2 decimal places can be checked using Math.round(tis.value*100)/100!=tis.value
Note:
I have used oninputto validate even in copy paste scenarios
function restrict(tis) {
var prev = tis.getAttribute("data-prev");
prev = (prev != '') ? prev : '';
if (Math.round(tis.value*100)/100!=tis.value)
tis.value=prev;
tis.setAttribute("data-prev",tis.value)
}
<input type="number" id="rText" oninput="restrict(this);" />
I love to use Math.floor and toFixed() to resolve my decimal issues.
Here is a example:
var value = 123.5555
var roundedNumber = (Math.floor(value * 100) / 100).toFixed(2)
roundedNumber will be "123.55" as a string. So if you want as a number just add:
var value = 123.5555
var roundedNumber = Number((Math.floor(value * 100) / 100).toFixed(2))
and now you have value as a number and fixed to up 2 decimal places.
Just copy paste this method and call this method on your respective button on which button you have to check this decimal validation.
function CheckDecimal(inputtxt)
{
var decimal= /^[-+]?[0-9]+\.[0-9]+$/;
if(inputtxt.value.match(decimal))
{
alert('Correct, try another...')
return true;
}
else
{
alert('Wrong...!')
return false;
}
}

JS calculation issue

I have a simple vat calculator, but there is something funny with one of the calculation. The problem is in the last column, saying moms. e=a + d * 0.25 is correct, but the code below is not. It shows a too big number when calculating.
JS Code:
$(document).ready(function() {
$('#submit').click(function() {
//get cost and check value
var cost = $('#cost').val();
var check = $('#checkBox');
if (cost != null && cost != "") {
if (cost < 350) {
//c = a * 1
$('#total').val(cost);
$('#toll').val("");
$('#moms').val("");
} else {
if (check.is(':checked')) {
//c = a* 1.107* 1.25
$('#total').val((cost * 1.107 * 1.25).toFixed(2));
//d = a * 0.107
$('#toll').val((cost * 0.107).toFixed(2));
} else {
$('#total').val((cost * 1.25).toFixed(2));
$('#toll').val("");
$('#moms').val("");
}
if ($('#toll').val() != null && $('#toll').val() != "") {
//e = (a + d) * 0.25
var moms = (cost + $('#toll').val()) * 0.25;
$('#moms').val(moms.toFixed(2));
}
}
}
})
});
The value of input elements will always be a string. In most of your code, you're using the "cost" value in such a way that it will be implicitly converted to a number. However, the + operator is different, and will preferentially perform string concatenation to addition.
If you explicitly force the cost to be a number when you initialize it, things should work better:
var cost = +$('#cost').val();
That leading unary + operator will force the string value to be treated as a number. Now, of course, if the string doesn't look like a good number, then cost will be set to NaN, so you should check for that:
if (!isNaN(cost)) {
That can replace your current check to see if cost is not empty.
edit Sorry, you'll also need to convert the value of $('#toll').val() so that line would look like:
var moms = (cost + +$('#toll').val()) * 0.25;
The JavaScript + operator really likes strings.

Javascript String indexOf not working as expected

I must be missing something .. not sure why my JavaScript is failing or not working
var discount = 10;
var newTemp;
if (discount != null) {
if (discount.indexOf("%") > -1) {
newTemp = discount.substring(0, 2) + '%';
} else {
newTemp = discount;
}
} //end of outer if
Above script works when discount = "10.0%"
But fails when discount = 10
maynot be best way, but all I am trying to do is if discount value contains % sign then setting newTemp variable with new value. Else just keep it as is.
Any idea, why control fails when discount value is = 10
because "10%" is a string, therefore it has a indexOf method, and 10 is probably an integer or number.
Try discount.toString().indexOf('%')
It's because you're not appending the '%' in the else branch.
var newTemp;
if (discount != null) {
if (discount.indexOf("%") > -1) {
newTemp = discount.substring(0, 2);
} else {
newTemp = discount;
}
} //end of outer if
newTemp += '%';
also as Hugo said, the number 10 does not have the indexOf method, which is a string method.

Javascript function formats number to return NaN

This bit of code in a JS file I am using which formats the number to add .00 on the end. Only issue is my number is 0.7321 and it returns NaN. Any idea how to modify it?
self.formatFloat = function (number) {
var split = number.toString().split('.');
var decimal = (split[1] !== undefined? split[1] : '') + (new Array(3-(split[1] !== undefined? split[1].length : 0))).join('0');
return split[0] + '.' + decimal;
};
#Felix-Kling should win this answer
self.formatFloat=function (number) {
return number.toFixed(2);
};
Use Math.round(num * 100) / 100

multiply two decimals

Im trying to add a tax field. I have this working for whole numbers but i need to be able to enter ".5"
I have no clue haw to solve this problem maybe its because of the isNAN but i thought this would be ok here.
http://jsfiddle.net/thetylercox/eeMva/3/
My current code
$(document).ready(function() {
calculateSum();
$(".txt").keyup(function() {
$(".txt").each(function() {
calculateSum();
});
});
});
$("#tax").keyup(function() {
$('#total1').val(parseInt($(this).val()) * parseInt($('#subtotal').val()));
);
function calculateSum() {
var sum = 0;
$("#sum").val(sum.toFixed(2));
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$("#sum").html(sum.toFixed(2));
var subtotal = document.getElementById("subtotal").value == "";
var subtotal = document.getElementById("subtotal").value = sum;
function getTax(tax) {
var taxFloat = parseFloat(tax)
if (isNaN(taxFloat)) {
return 1;
} else {
return taxFloat;
}
}
var total = getTax($('#tax').val()) * sum;
var total1 = document.getElementById("total1").value = total;
} ​
Thanks
Try this:
Put all code including functions inside your $(document).ready(function(){...}) structure.
Perform all calculations, including tax, inside calculateSum().
Use jQuery all through, in particular '$(...)' in preference to .getelementById(...).
Attach calculateSum as the 'keyup' handler for all the user-enterable fields.
Purge all sorts of junk from the code
It should look like this :
$(document).ready(function(){
function getTax() {
var taxFloat = parseFloat($("#tax").val());
return isNaN(taxFloat) ? 1 : taxFloat;
}
function calculateSum() {
var sum = 0;
$(".txt").each(function() {
if (this.value && !isNaN(this.value)) {
sum += parseFloat(this.value);
}
});
$("#subtotal").val(sum.toFixed(2));
$("#total1").val((getTax()*sum).toFixed(2));
}
$(".txt, #tax").keyup(calculateSum);
});
DEMO
You probably want to change the tax algorithm to something more logical. eg. for an entered value of 5(%), the multiplier should be 1.05 .
Taxes are based on percentages. Do the following changes:
$("#tax").keyup(function() {
//$('#total1').val(parseInt($(this).val()) * parseInt($('#subtotal').val()));
calculateSum();
});
...
function getTax(tax) {
var taxFloat = parseFloat(tax)
if (isNaN(taxFloat)) {
return 1;
} else {
// 1(subtotal) + ?(tax%) -> total = (1 + tax%) * subtotal
return 1 + (taxFloat/100);
}
}
var total = getTax($('#tax').val()) * sum;
// round to 2 decimal digits
total = Math.round(total * Math.pow(10, 2)) / Math.pow(10, 2);
var total1 = document.getElementById("total1").value = total;
So for 5% you enter 5 for 0.5% you enter .5
UPDATE: (Not really an update) As I see more answers coming in, I repeat the logical error for tax field usage. Taxes are percentages worldwide, Meaning that the problem was not only the keyup handling, but also the way tax value was used.
Found your error:
$("#tax").keyup(function() {
$('#total1').val(parseInt($(this).val()) * parseInt($('#subtotal').val()));
});
Here, you parse the tax with parseInt instead of parseFloat, as you do in the function getTax. parseInt(".5") gives NaN. Try to insert values in the .txt inputs after having inserted a tax, and it would work when invoking the calculateSum function.
I can't understand why you would use a different computation when pressing keys in the #tax field than on normal keypresses in other fields. Just use the same listener function, or, if you want to divide the functionality, invoke the function to display the tax both from the #tax keyhandler and the calculateSum function.
Also, there is no need to execute calculateSum() four times when one of the inputs is updated.
See better structured source code in updated fiddle. The maths to calculate taxes and totals was not corrected.

Categories

Resources