Select number then format to 2 decimal places - javascript

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

Related

JavaScript returns different output for same parameter values

I have the below JavaScript code to round the values, which returns different result in similar cases. This is being called through a tool.
var precision = -1;
/**
* Initialization
*/
function _init()
{
precision = 8;
}
case1
function RoundUp(number, num_digits)
{
var shift = Math.pow(10, num_digits);
var rounded = Math.ceil(number * shift) / shift;
rounded = (precision>-1) ? Number(rounded.toFixed(precision)) : rounded;
return rounded;
}
case2
function RoundUp(110, 1)
{
var shift = Math.pow(10, num_digits);
var rounded = Math.ceil(number * shift) / shift;
rounded = (precision>-1) ? Number(rounded.toFixed(precision)) : rounded;
return rounded;
}
If we directly pass some parameter values, ex (110,1), it returns 110. (CASE2) But when we pass the same parameter values indirectly through some variable (CASE1), the output changes to 111 for some reason.
Here, number = 110 and num_digits = 1
I cant figure out why this is the case. Can someone please help. Pardon me, but I am new to JavaScript.
Thanks
It's not entirely clear what you're actually trying to do. However, you appear to have two problems.
1. Syntax error
This line:
function RoundUp(110, 1)
is not a legal JavaScript statement. You cannot pass values to a function while you're defining it. What JavaScript thinks you're trying to do here is define a function with two parameters called 110 and 1, which are both illegal parameter names, so you get a syntax error.
2. Math
I'm assuming that what you're trying to do is this:
roundUp(12345, 1) => 20000
roundUp(12345, 2) => 13000
roundUp(12345, 3) => 12400
roundUp(12345, 4) => 12350 etc
If that's correct, then your math is wrong. Try this instead:
function roundUp(number, numDigits) {
var shift = Math.pow(10, number.toString().length - numDigits);
var rounded = Math.ceil(number / shift) * shift;
rounded = (precision>-1) ? Number(rounded.toFixed(precision)) : rounded;
return rounded;
}
This will not work for floating-point numbers, but if you only need to deal with integers it's fine.

numbers and text in same field

I can't get the numbers and text in same form field to force two decimal places or do Total figure.
This is the link.
I am trying to get the last 3 cells to work with two decimal places.
e.g. Total sq mt figure x Price should calculate the Cost cell.
Also want to get the Cost cell (NaN) working !
Thanks.
In general, you want to do something like this
function calc(val1, val2) { // this is NOT a replacement for your Calculate function
val1 = parseFloat(val1.replace(/[^\d\.-]/g, ''));
val2 = parseFloat(val2.replace(/[^\d\.-]/g, ''));
return (val1 * val2).toFixed(2);
}
NOTE: the above returns a STRING
and STOP redefining with Math.round in your code
var result = Math.round(num * 100.0) / 100.0;
Should format your number with two decimal places.

Tapering/Rounding decimal answers JS calculations

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"

Why do some rounded JavaScript values round the wrong way?

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/

JavaScript - Moving decimal place to the right

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");

Categories