I'm trying to get the decimal place to move to the right and give me at least a 2 digit whole number. I've got the places after the decimal figured out, but not before the decimal.
The input value is divided by 36 and it's supposed to result in a percentage.
There's a fiddle here...
$(function() {
var output_element = $('#creditRemaining');
$('#creditRemaining').keyup(function() {
updateTotal();
});
var updateTotal = function () {
var input1 = parseInt($('#creditRemaining').val() || 0);
$('#total').text((input1 / 36).toFixed(2) + "% Prorated");
};
});
Thoughts?
Multiply it by 100 and then use .toFixed(2)
Then this line looks like this:
$('#total').text(((input1 / 36)*100).toFixed(2) + "% Prorated");
Related
I am currently trying to calculate fees that my service charges for sales (8%). The seller can input the amount they want to receive, or want's the buyer to pay (Like Steam does here: http://i.imgur.com/pLFN9px.png). I am currently using this code:
function precise_round(num, decimals) {
var t=Math.pow(10, decimals);
return (Math.round((num * t) + (decimals>0?1:0)*(Math.sign(num) * (10 / Math.pow(100, decimals)))) / t).toFixed(decimals);
}
var elem = $(this);
elem.data('oldVal', elem.val());
elem.bind("propertychange change click keyup input paste", function(event){
if (elem.data('oldVal') != elem.val()) {
elem.data('oldVal', elem.val());
if(elem.attr("id")=="seller-gets") {
var cur = elem.val();
var value = cur*1.08;
$("#buyer-pays").val(precise_round(value), 2);
} else {
var cur = elem.val();
var value = cur*0.92;
$("#seller-gets").val(precise_round(value), 2);
}
}
});
});
The Receive(Left) <--> Pay(Right) conversions are not consistent. (Putting the same number the left produced back into the right gives a different left).
Sorry if this is not clear enough, I can explain it a little better if needed.
Those are inconsistent before you are doing two different things. Say for eg. lets take 5 as the left number.
8% of 5 = .4, So Right number will be 5.4
And if you put 5.4 as the right number 8% of it is .432 not .4. So the left number will be 5.4 - .432 = 4.968 and not 5.
If you want to get back the same number then you have to multiply by 1.08 for left -> right conversion and divide by 1.08 for the vice-versa.
Hope this helps.
Firstly, can you be sure that the values that are passed to the precise_round function are what you expect?
If not, then I think from looking at your code that you need to convert the raw values to float. I have had the same problem with values being one cent wrong, and converting to float fixed it.
var value = cur*1.08;
should be:
var value = parseFloat(cur)*1.08;
and
var value = cur*0.92;
should be:
var value = parseFloat(cur)*0.92;
After that, you can use value.toFixed(2) instead of rounding. Something to try anyway.
Using JS to run a simple formula, but like many JS calculations I've made before the decimal answers go on for way longer than I'd like and make it look sloppy.
Is there I way I can force the calculation to stop at a certain decimal place or force a round up from there?
Thanks!
<script>
var $u = $('input[name=u]');
var $a = $('input[name=a]');
var $h = $('input[name=h]');
$u.on('keyup',function() {
var u = +$u.val();
var a = +$a.val();
$h.val(u*4.605+a*1.308+28.003).toFixed(1);
});
$a.on('keyup',function() {
var u = +$u.val();
var a = +$a.val();
$h.val(u*4.605+a*1.308+28.003).toFixed(1);
});
</script>
I see you've tried toFixed(). I believe that is the solution, but you're trying to call it on a jQuery object. You should call it on the number before passing it into val().
Change your code to:
$a.on('keyup',function() {
var u = +$u.val();
var a = +$a.val();
$h.val((u*4.605+a*1.308+28.003).toFixed(1));
});
// $('#a').val(Math.PI).toFixed(1); // You're inserting the full value, and then executing
// toFixed on a jQuery Object. Not going to work.
$('#a').val( (Math.PI).toFixed(1) ); // How it should be written
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input id="a"/>
Math.floor(number)
Returns the next integer below given number.
Math.floor(1.66); // 1
Math.floor(-1.66); // -2
Math.ceil(number)
Returns the next integer above given number.
Math.ceil(1.66); // 2
Math.ceil(-1.66); // -1
Math.round(number)
Returns the nearest integer. Similar to Math.floor(number + 0.5);
Math.round(1.66); // 2
Math.round(-1.66); // -2
number|0 (or ~~number)
Discards the decimal portion of a number.
1.66|0; // 1
-1.66|0; // -1
number.toFixed(decimals)
Converts a number into a string with the specified number of decimals. Will either pad the result with zeroes or mathematically round to a certain number of decimals.
(1.66).toFixed(1); // "1.7"
(-1.66).toFixed(1); // "-1.7"
number.toFixed(decimals + 1).slice(0, -1)
Returns a fixed-decimal string, but chops the specified number of decimals without rounding.
(1.66).toFixed(2).slice(0, -1); // "1.6"
I am trying to write some code that will do the following;
Add an ID to nth child
Format the number in nth child to 2 decimal places
Apply £ in front of the numbers
Loop until every nth child in a table is done
I have numbers such as this to round of “0.7823076923076923” using the code I have I can get it to round up to "1" but I need it to round to 0.78 I then added “toFixed(2)” and it takes my “1” and puts it to “1.00” but I need It to go to “0.78” once I have that in place I can then look at how I can loop the code, but small steps.
Thanks for all the help.
Code:
<script>
$(document).ready(function(){
$('table>tbody>tr>td:nth-child(5n)').prop('id', 'test');
$('#test').text(function(i,v) {
return Math.round(parseInt(v * 100) / 100).toFixed(2);
});
});
</script>
UPDATE
i got it working!!!
$(document).ready(function(){
$('table>tbody>tr>td:nth-child(5n)').prop('id', 'test');
var test = parseFloat($('#test').text()).toFixed(2);
$('table>tbody>tr>td:nth-child(5n)').empty().append(test);
});
now to make it loop,
Thanks for all the help.
To round a number to n decimal places:
var n = 2;
var number = 0.7823076923076923;
var result = Math.round(number * Math.pow(10,n)) / Math.pow(10,n);
result = result.toFixed(n);
UPDATE:
For a more reusable option, you can define a custom rounding function:
function roundTo (value, n) {
var result = Math.round(value * Math.pow(10,n)) / Math.pow(10,n);
return result.toFixed(n);
}
var foo = roundTo(0.7823076923076923, 2); // 0.78
I have tried numerous scripts after 1 hour and half of googling and all have either given me the wrong rounded number or the wrong value altogether. These are two scripts I tried.
FIRST TRY:
Number.prototype.round = function(p) {
p = p || 10;
return parseFloat( this.toFixed(p) );
};
SECOND TRY:
function roundNumber(number, decimals) {
var newnumber = new Number(number+'').toFixed(parseInt(decimals));
return parseFloat(newnumber);
}
Some Example Outputs that I get from both:
0.22 -> 0.21480000000000005 (bad) should be 21
0.43 -> 0.4284 (good) 43 is right
What am I doing wrong? Any help would be appreciated as this has had me poking for too long.
Why not use something like this:
Math.round(yourNumber * 100) / 100;
This will round it to two decimal places, the same question was more or less answered here - Round to at most 2 decimal places (only if necessary)
Here is a small example
function round(num){
var result = Math.round(num * 100) / 100;
return console.log(result);
}
round(0.4284);
The Fiddle is here to test: https://jsfiddle.net/ToreanJoel/bLzz2mL8/
I have retrieved a string and I extracted a decimal number from it using regex, e.g. 1.00 or 3.99. Now I wanna use these numbers for calculation. How can I convert those regex results into proper numbers so I can perform calculation? In the code below, every click should add the price to the previous total but it doesn't do the sum of numbers properly.
var SaveAfrica = {
init: function () {
this.addToBasket();
},
addToBasket: function () {
var featured = $('section.featured'),
bsktTotalSpan = $('.basket_total span.basket-qty'),
list = featured.find('ul'),
item = list.find('li');
featured.delegate('.buy-now', 'click', function (e) {
var thisElem = $(this),
qtyData = thisElem.closest('li').data('price'),
total = parseInt(bsktTotalSpan.text()) + parseFloat(qtyData.match(/[\d\.\d]+/i));
e.preventDefault();
bsktTotalSpan.text(parseFloat(total));
console.log('The total is: total);
});
}
};
SaveAfrica.init();
The HTML where the digit is from:
<li data-price="£2.99"><img src="someImage.jpg" alt="some image" /></li>
Many thanks
Your problem may be that .match() returns an array of matches. So you might try something like:
parseFloat(qtyData.match(/[\d\.\d]+/i)[0]);
What does the sum come out to, if anything at all?
You may want to try the following instead:
total = parseFloat(bsktTotalSpan.text()) + parseFloat(qtyData.match(/[\d\.\d]+/i));
That is, parse both of them to floats And explicitly define total as a float. Otherwise, the decimals might be getting truncated somewhere.
I think there is a typo in while getting the price from the element.
The code should be as below,
qtyData = thisElem.closest('li').data('data-price'),
You can simply multiply the string by 1 in order to convert it into a number:
num = '1.00' * 1 //result is the number 1