Math Round Function - javascript

I'm using a form that use the following script to calculate the item price including VAT:
function calculateTotaleIVA() {
var tot = document.getElementById('totale').value;
document.getElementById('totale_prodotto').value = Math.round(tot*121)/100;
totale_prodotto.value = document.getElementById('totale_prodotto').value.replace(".", ",");
totale.value = document.getElementById('totale').value.replace(".", ",");
}
This function works fine but I have a questions. Some times the result is like this:
46,4
I want to see at screen two digits after point decimal like this:
46,40
How can I fix the above function to solve it?
Thanks in advance.

Use toFixed
(Math.round(tot*121)/100).toFixed(2)

you can use toFixed(2) for that
toFixed(No of digits)
(Math.round(tot*121)/100).toFixed(2);
see here

Related

jquery convert price from 5 decimals to round up to 2 decimals

I have a price number that looks like this: $27,272.70000
I'm trying to make it look like this: $27,272.70
I'm stuck with trying different methods but here is what i've got so far:
jQuery(document).ready(function() {
jQuery('.cart-table-wrapper #shopping-cart-table tbody > tr').each(function() {
var the_sp_subtotal = jQuery(this).find('td.col-total.a-right span.price').text().replace("$", "");
var new_sp_subtotal = parseFloat(the_sp_subtotal).toFixed(2);
console.log(new_sp_subtotal);
});
});
But the result that I get is: 27.00
Here is the fiddle - https://jsfiddle.net/zqe37xsk/1/
Can someone please help me, what I'm doing wrong?
Thank you
To format a currency string properly you could use the toLocaleString function. For this to properly work you have to transform your string into a float.
var price = '27,272.70000';
price = parseFloat(price.replace(/[$,]/g, ""));
console.log(price.toLocaleString('us-EN', {
style: 'currency',
currency: 'USD'
}));
parseFloat("27,272.70") returns 27 because the , in 27,272.70 is no longer part of a number.
As an alternative approach you could replace the part behind the last thousands separator and call toFixed on that. Then you can just join everything back together.
In your each function, use:
const [dollar, ...separatedNumber] = jQuery(this).find('td.col-total.a-right span.price').text().split(/\$|,/);
separatedNumber[separatedNumber.length - 1] = Number(separatedNumber.slice(-1)).toFixed(2);
console.log("$" + separatedNumber.join(","));

JavaScript add decimal without using toFixed() method

I've got some values that are appended with 00's for cents by PHP. I need to add a decimal point to them.
val = 10000 (needs to turn into 100.00);
val.toFixed(2) = 10000.00 (no bueno);
val.magic() = 100.00 (perf!)
Thanks!
(val/100).toFixed(2) = 100.00;
If you have a string value in cents, a simple regular expression can be used to insert a decimal point:
function addPoint(s) {
return s.replace(/(\d\d)$/,'.$1');
}
var s = '1000';
alert(addPoint(s)); // 10.00

Round off the results to two decimal places

I'm working on my javascript. I want it to sum in two decimal places. So if I add:
25.321+300.693 = 326.014
I want the sum to be: 326.01. Here's my code:
function civ(){
civ1=Number(document.addition.scc.value);
civ2=Number(document.addition.ccc.value);
civ3=Number(document.addition.ncc.value);
civ4=Number(document.addition.vch.value);
civ5=Number(document.addition.mch.value);
civ6=Number(document.addition.nlch.value);
civ7=Number(document.addition.slch.value);
valNum1=civ1+civ2+civ3+civ4+civ5+civ6+civ7;
document.addition.civ123.value=valNum1;
}
I also try this one:
function civ(){
civ1=Number(document.addition.scc.value);
civ2=Number(document.addition.ccc.value);
civ3=Number(document.addition.ncc.value);
civ4=Number(document.addition.vch.value);
civ5=Number(document.addition.mch.value);
civ6=Number(document.addition.nlch.value);
civ7=Number(document.addition.slch.value);
valNum1=Math.round(civ1+civ2+civ3+civ4+civ5+civ6+civ7*100)/100;
document.addition.civ123.value=valNum1;
}
But the result is incorrect. I add 2 numbers again (128.65 + 0 ) = 1.29 or 1.28 (I forgot). Thanks for those who will help.
order of operations...
Math.round((civ1+civ2+civ3+civ4+civ5+civ6+civ7)*100)/100;
Try this:
var num = 15.65686354785
var newnum = (num.toString().length > 4 ? num.toFixed(2) : num);
try this
valNum1=Math.round((civ1+civ2+civ3+civ4+civ5+civ6+civ7)*100)/100;
you misplace the braces

JavaScript displaying a float to 2 decimal places

I wanted to display a number to 2 decimal places.
I thought I could use toPrecision(2) in JavaScript .
However, if the number is 0.05, I get 0.0500. I'd rather it stay the same.
See it on JSbin.
What is the best way to do this?
I can think of coding a few solutions, but I'd imagine (I hope) something like this is built in?
float_num.toFixed(2);
Note:toFixed() will round or pad with zeros if necessary to meet the specified length.
You could do it with the toFixed function, but it's buggy in IE. If you want a reliable solution, look at my answer here.
number.parseFloat(2) works but it returns a string.
If you'd like to preserve it as a number type you can use:
Math.round(number * 100) / 100
Don't know how I got to this question, but even if it's many years since this has been asked, I would like to add a quick and simple method I follow and it has never let me down:
var num = response_from_a_function_or_something();
var fixedNum = parseFloat(num).toFixed( 2 );
with toFixed you can set length of decimal points like this:
let number = 6.1234
number.toFixed(2) // '6.12'
but toFixed returns a string and also if number doesn't have decimal point at all it will add redundant zeros.
let number = 6
number.toFixed(2) // '6.00'
to avoid this you have to convert the result to a number. you can do this with these two methods:
let number1 = 6
let number2 = 6.1234
// method 1
parseFloat(number1.toFixed(2)) // 6
parseFloat(number2.toFixed(2)) // 6.12
// method 2
+number1.toFixed(2) // 6
+number2.toFixed(2) // 6.12
Try toFixed instead of toPrecision.
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // return 1.01
round(1.004, 2); // return 1 instead of 1.00
The answer is following this link: http://www.jacklmoore.com/notes/rounding-in-javascript/
I used this way if you need 2 digits and not string type.
const exFloat = 3.14159265359;
console.log(parseFloat(exFloat.toFixed(2)));
You could try mixing Number() and toFixed().
Have your target number converted to a nice string with X digits then convert the formated string to a number.
Number( (myVar).toFixed(2) )
See example below:
var myNumber = 5.01;
var multiplier = 5;
$('#actionButton').on('click', function() {
$('#message').text( myNumber * multiplier );
});
$('#actionButton2').on('click', function() {
$('#message').text( Number( (myNumber * multiplier).toFixed(2) ) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button id="actionButton">Weird numbers</button>
<button id="actionButton2">Nice numbers</button>
<div id="message"></div>
The toFixed() method formats a number using fixed-point notation.
and here is the syntax
numObj.toFixed([digits])
digits argument is optional and by default is 0. And the return type is string not number. But you can convert it to number using
numObj.toFixed([digits]) * 1
It also can throws exceptions like TypeError, RangeError
Here is the full detail and compatibility in the browser.
let a = 0.0500
a.toFixed(2);
//output
0.05
There's also the Intl API to format decimals according to your locale value. This is important specially if the decimal separator isn't a dot "." but a comma "," instead, like it is the case in Germany.
Intl.NumberFormat('de-DE').formatToParts(0.05).reduce((acc, {value}) => acc += value, '');
Note that this will round to a maximum of 3 decimal places, just like the round() function suggested above in the default case. If you want to customize that behavior to specify the number of decimal places, there're options for minimum and maximum fraction digits:
Intl.NumberFormat('de-DE', {minimumFractionDigits: 3}).formatToParts(0.05)
float_num = parseFloat(float_num.toFixed(2))
I have made this function. It works fine but returns string.
function show_float_val(val,upto = 2){
var val = parseFloat(val);
return val.toFixed(upto);
}

simple calculation of integer and decimal number in jquery

Trying to multiply 2 values. Quantity is integer and credit price is decimal number. When I run this code nothing happens.
Does anyone know what is the issue?
Thank you.
$(function(){ // bind the recalc function to the quantity fields
$("#oneCreditSum").after('<label></label>Total: Aud <span id=\"total\"></span><br><br>');
$("#quantity").bind('keyup', recalc);
function recalc(){
var quantity = $('#quantity').val();
var creditPrice = $('#creditPrice').val();
var total = quantity * creditPrice;
$("#total").text(total);
}});
Use parseFloat on the values, and alert each one individually to test.
A few other (unrelated) improvements:
Use keyup() function:
$("#quantity").keyup(recalc);
Make function anonymous:
$("#quantity").keyup(function(){...});
Use $(this) on #quantity in the function to avoid calling the jQuery selector again
You could also consider condensing this into a single line of code:
$("#total").text(parseFloat($('#quantity').val()) * parseFloat($('#creditPrice').val()));
To zero-pad you might try something toFixed():
var num = 10;
var result = num.toFixed(2); // result will equal 10.00
I got this snippet from the following site
http://www.mredkj.com/javascript/numberFormat.html
Hope this helps.
use
parseFloat
before calculation on both numbers which parses a string argument and returns a floating point number.
var quantity = $('#quantity').val();
var creditPrice = $('#creditPrice').val();
var total = parseFloat(quantity) * parseFloat(creditPrice);
If you are interested in whole number only you can use this function instead:
parseInt

Categories

Resources