Multiply numbers with more than 4 decimal points [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
round number in JavaScript to N decimal places
This may be easy for you guys,
My question is:
How can I control a decimal places in a floating point value.
Ex.: My result is returning 0.365999999999999; but I need to show just 4 decimal numbers.
Check the demo: Demo (I accept any others ways to calculate that)
Thanks!

You can use .toFixed
var number = 0.365999999999999;
var rounded = number.toFixed(4); // 0.3660

try this:
$("#test").keyup(function(){
var number = parseFloat($("#number").text());
var current = parseFloat($(this).val());
var total = number*current;
$("#result").val(total.toFixed(4));
});

$("#result").val(total.toFixed(4));

Javascript has a nice round function, but it only does integers so you have to multiply it by 10000 then divide the rounded result by 10000
http://www.javascriptkit.com/javatutors/round.shtml
The toFixed function always rounds up, but round will probably do what you want.

For proper rounding:
function roundNumber(number, digits) {
var multiple = Math.pow(10, digits);
var rndedNum = Math.round(number * multiple) / multiple;
return rndedNum;
}
For rounding up:
number.toFixed(4);

$("#test").keyup(function(){
var number = $("#number").text();
var current = $(this).val();
var total = parseFloat(number*current).toFixed(2);
$("#result").val(total);
});
Cast the variable to a float and then use the toFixed() method

If you follow the link below you can import the number_format php function to javascript. The function has been helping me for years now.
Here is the function signature :
function number_format (number, decimals, dec_point, thousands_sep)
http://phpjs.org/functions/number_format:481

Related

PHP round($num,2) and javascript toFixed(2) is not giving right output for this value 53.955

I have one php function and having
phpans = round(53.955,2)
and javascript function
var num = 53.955;
var jsans = num.toFixed(2);
console.log(jsans);
both jsans and phpans is giving different $phpans = 53.96 ans jsans = 53.95 . I can not understand why this is happening ..
Thanks is Advance
Because computers can't represent floating numbers properly. It's probably 53.95400000000009 or something like that. The way to deal with this is multiply by 100, round, then divide by 100 so the computer is only dealing with whole numbers.
var start = 53.955,
res1,
res2;
res1 = start.toFixed(2);
res2 = (start * 100).toFixed(0) / 100;
console.log(res1, res2);
//Outputs
"53.95"
53.96
JAvascript toFixed:
The toFixed() method converts a number into a string, keeping a specified number of decimals.
php round:
Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
Conclusion tofixed not working like php round. precision Specifies the number of decimal digits to round to.
Javascript function :
function round_up (val, precision) {
power = Math.pow (10, precision);
poweredVal = Math.ceil (val * power);
result = poweredVal / power;
return result;
}

Rounding a number up [duplicate]

This question already has answers here:
Rounding numbers to 2 digits after comma
(10 answers)
Closed 9 years ago.
I want to round the up my total til two decimal places.
I have this:
var updateTotal = function () {
var people = parseInt($('#people').val());
var bill = parseInt($('#bill').val());
var tip = parseInt($('#tip').val());
var billTip = bill + tip;
$('#total').text(billTip / people);
and i've also found this snippet to help round up but i cant seem to get my head around how to implement it.
var rounded = Math.round((10 / 3) * 100) / 100;
Thanks
It's already implemented for you. Substitue (10 / 3) for your own variables. All it's doing is shifting the decimal place two places to the right (by multiplying by 100), rounding, then shifting it two left (by dividing by 100).
var rounded = Math.round((billTip / people) * 100) / 100;
You can also use .toFixed
$('#total').text((billTip / people).toFixed(2));
I would use parseFloat on both your numbers, or else it will round to 00:
$('#total').text(parseFloat(billTip / people).toFixed(2));
You can use ceil function Math.ceil(billTip)
and for refernce you can also visit below link
http://www.w3schools.com/jsref/jsref_ceil.asp

how to get 1.450 = 1.5 in javascript? (round to 1 decimal place) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you round to 1 decimal place in Javascript?
My Value is 1.450 and I have to round it to 1 decimal place.
I want 1.450 = 1.5 in Javascript can any body fix this please.
You need this:
var mynum = 1.450,
rounded = Math.round(mynum * 10) / 10;
suppose you have
var original=28.453;
Then
var result=Math.round(original*10)/10 //returns 28.5
From http://www.javascriptkit.com/javatutors/round.shtml
You can also see How do you round to 1 decimal place in Javascript?
Given your fiddle, the simplest change would be:
result = sub.toFixed(1) + "M";
to:
result = Math.ceil(sub.toFixed(1)) + "M";
If you use Math.round then you will get 1 for 1.01, and not 1.0.
If you use toFixed you run into rounding issues.
If you want the best of both worlds combine the two:
(Math.round(1.01 * 10) / 10).toFixed(1)
You might want to create a function for this:
function roundedToFixed(_float, _digits){
var rounder = Math.pow(10, _digits);
return (Math.round(_float * rounder) / rounder).toFixed(_digits);
}

Input field values not adding up correctly [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is JavaScript's Math broken?
I'm attempting to add up three input fields, each containing a value of 33.3 which should total 99.9, however they are totaling to 99.89999999999999
Could someone explain how this is happening. Below is my code. Thanks in advance.
$("#modify-funding input.percentCalc").sumValues()
$.fn.sumValues = function () {
var sum = 0;
this.each(function () {
sum += $(this).fieldVal();
});
return sum;
};
$.fn.fieldVal = function () {
var val;
if ($(this).is(':input')) {
val = $(this).val();
alert("val " + val);
} else {
val = $(this).text();
}
return parseFloat(('0' + val).replace(/[^0-9-\.]/g, ''), 10);
};
Welcome to the wonderful world of floating point numbers. Floating points are aproximations of the number you want to represent. Thus when you save a number as 33.3 it is around but not exactly 33.3 this error adds up after multiple operations. The best way to compare floats is to not test for equality but to test weather they are in a range.
Instead of
if(x == 99.9)
try
if(Math.abs(99.9 - x) < .1)
If you just want the string representation. You could try handing the floating point number as an integer. i.e. 33.3 equals 333 then when you are turning it back into a string you add the decimal back in where appropriate. This would be the best solution for your problem.

How do I round a number in JavaScript?

While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of
Name : Value
Name2 : Value2
etc.
The peoblem is that the values can sometimes be floats (with different precision), integers, or even in the form 2.20011E+17. What I want to output are pure integers. I don't know a lot of JavaScript, though. How would I go about writing a method that takes these sometimes-floats and makes them integers?
If you need to round to a certain number of digits use the following function
function roundNumber(number, digits) {
var multiple = Math.pow(10, digits);
var rndedNum = Math.round(number * multiple) / multiple;
return rndedNum;
}
You hav to convert your input into a number and then round them:
function toInteger(number){
return Math.round( // round to nearest integer
Number(number) // type cast your input
);
};
Or as a one liner:
function toInt(n){ return Math.round(Number(n)); };
Testing with different values:
toInteger(2.5); // 3
toInteger(1000); // 1000
toInteger("12345.12345"); // 12345
toInteger("2.20011E+17"); // 220011000000000000
According to the ECMAScript specification, numbers in JavaScript are represented only by the double-precision 64-bit format IEEE 754. Hence there is not really an integer type in JavaScript.
Regarding the rounding of these numbers, there are a number of ways you can achieve this. The Math object gives us three rounding methods wich we can use:
The Math.round() is most commonly used, it returns the value rounded to the nearest integer. Then there is the Math.floor() wich returns the largest integer less than or equal to a number. Lastly we have the Math.ceil() function that returns the smallest integer greater than or equal to a number.
There is also the toFixed() that returns a string representing the number using fixed-point notation.
Ps.: There is no 2nd argument in the Math.round() method. The toFixed() is not IE specific, its within the ECMAScript specification aswell
Here is a way to be able to use Math.round() with a second argument (number of decimals for rounding):
// 'improve' Math.round() to support a second argument
var _round = Math.round;
Math.round = function(number, decimals /* optional, default 0 */)
{
if (arguments.length == 1)
return _round(number);
var multiplier = Math.pow(10, decimals);
return _round(number * multiplier) / multiplier;
}
// examples
Math.round('123.4567', 2); // => 123.46
Math.round('123.4567'); // => 123
You can also use toFixed(x) or toPrecision(x) where x is the number of digits.
Both these methods are supported in all major browsers
You can use Math.round() for rounding numbers to the nearest integer.
Math.round(532.24) => 532
Also, you can use parseInt() and parseFloat() to cast a variable to a certain type, in this case integer and floating point.
A very good approximation for rounding:
function Rounding (number, precision){
var newNumber;
var sNumber = number.toString();
var increase = precision + sNumber.length - sNumber.indexOf('.') + 1;
if (number < 0)
newNumber = (number - 5 * Math.pow(10,-increase));
else
newNumber = (number + 5 * Math.pow(10,-increase));
var multiple = Math.pow(10,precision);
return Math.round(newNumber * multiple)/multiple;
}
Only in some cases when the length of the decimal part of the number is very long will it be incorrect.
Math.floor(19.5) = 19 should also work.

Categories