Input field values not adding up correctly [duplicate] - javascript

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.

Related

Javascript to turn 110,000 into 110K and not 0.11M [duplicate]

This question already has an answer here:
Format a javascript number with a Metric Prefix like 1.5K, 1M, 1G, etc [duplicate]
(1 answer)
Closed 7 years ago.
To start with you need...
function m(n,d){x=(''+n).length,p=Math.pow,d=p(10,d)
x-=x%3
return Math.round(n*d/p(10,x))/d+" kMGTPE"[x/3]}
Then calling like so...
// m( ANY NUMBER HERE or VAR LIKE I USE,HOW DECIMAL PLACES)
m(110000,2)
However instead of the above's result of 0.11M, I would like it to display 110k.
What you have there is an example of an overly optimized script, lets make it more developer friendly an readable
function metricPrefix(rawNumber,decimalPlaces){
var sufixes= " kMFGPE";
var numberLength =(''+n).length;
decimalPlaces=Math.pow(10,d); //raise 10 to the number of decimal places
var modLen = numberLength - numberLength%3;
var sufix = sufixes[modLen/3];
return Math.round(rawNumber*decimalPlaces/decimalPlaces(10,modLen))/decimalPlaces+ sufix;
}
Now it's easier to work with. We can see the issue is that we need to adjust for when the string is divisible by 3, so lets fix that.
function metricPrefix(rawNumber,decimalPlaces){
var sufixes= " kMFGPE";
var numberLength =(''+rawNumber).length;
decimalPlaces=Math.pow(10,decimalPlaces); //raise 10 to the number of decimal places
//THis is the change
//If the length is divisable by 3 take 3 off the length
var modLen = numberLength%3 == 0 ? numberLength - 3 - (numberLength%3) : numberLength - (numberLength%3);
console.log(modLen);
var sufix = sufixes[(modLen/3)]
console.log(sufix)
return Math.round(rawNumber*decimalPlaces/Math.pow(10,modLen))/decimalPlaces+ sufix;
}
$(document).ready(function(){
$("#result").html(metricPrefix(110000,2));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>

JavaScript check if number is whole [duplicate]

This question already has answers here:
How do I check that a number is float or integer?
(52 answers)
Closed 7 years ago.
im trying to check if a number is a whole after a calculation. What I have so far prints out how many times one number gets divided by another, but when the number is not whole it dose not print anything out. Heres my code:
function round() {
var percent = document.getElementById('percent_sale').value;
var perShare = document.getElementById('singleShare').value;
var result = (percent / perShare);
if(result % 1 == 0) {
document.getElementById('results1').innerHTML = ('Number of shares:'+result);
} else {
document.getElementById(results1).innerHTML = ('number of shares must ');
}
}
The values get input buy a user, and the percent for sale is say 50 and the single share is say 2.5 this would return 20 shares.
What I need is if I put in something like 50 for sale and 3.15 single share it tells the user to make equal number of shares as it would return 15.87
Any ideas where ive gone wrong?
Convert your number into string and then check if the string contains only numbers
var num = 15;
var n = num.toString();
This will convert it into string then this
String.prototype.isNumber = function(){return /^\d+$/.test(this);}
console.log("123123".isNumber()); // outputs true
console.log("+12".isNumber()); // outputs false
For further reference.Link StackOverFlow

Is there a better way to convert negative numbers to positive in JavaScript? [duplicate]

This question already has answers here:
Get the absolute value of a number in Javascript
(6 answers)
Closed 7 years ago.
Problem: some numbers are positive some are not. Here is my function to convert negative numbers to positive ones and leave positive numbers untouched. Is there a better way of doing it in JavaScript?
function intAbs(integer) {
if(isNaN(integer)) {
throw 'NaN';
}
if(parseInt(integer, 10) !== integer) {
throw 'Not an integer';
}
n = integer * integer;
var x = 1;
var e = 1;
while(!(e < 0.1 && e > -0.1)) {
x = (n / x + x) / 2;
e = n - x * x;
}
return parseInt(x);
}
Update: I don't think this question is a duplicate. I know how to get the absolute value of an integer without Math.abs(). You can see in this question. I have already accepted the answer which states "Yes, there is a better way" and it's not ambiguous.
Update #2: This question is marked as a duplicate of Get the absolute value of a number in Javascript, but this does not address problem if(is there a better way of calculating abs than exactly this algorithm). I give up.
Yes, there is a better way: Math.abs().

Multiplication results in unusual decimal places [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is JavaScript’s Floating-Point Math Broken?
I have a strange mathematical problem during a multiplication in javascript.
$(parent).find('#id_deals-' + i + '-quantity').val()
result -> 10
$(parent).find('#id_deals-' + i + '-price').val()
result -> 3.99
Both above mulltiplied like this:
$(parent).find('#id_deals-' + i + '-price').val() * $(parent).find('#id_deals-' + i + '-quantity').val()
result --> 39.900000000000006
Why is this happening? and what can I do to limit the decimal places to 2 digits only?
Is it maybe because 10 has to be 10.0 ? But how do I convert my value to this format automatically before the actual multiplication?
Update:
According to syazdani's answer, I have tried to implement bigdecimal as suggested:
It is not well documented, but I got it working like this:
function run(opts) {
var bd = {"BigDecimal":BigDecimal, "BigInteger":BigInteger, "RoundingMode":RoundingMode};
var result;
var ops = {'*': "multiply", '/': "divide", '+': "add", '-': "subtract"};
var a = new bd.BigDecimal("" + opts.a);
var b = new bd.BigDecimal("" + opts.b);
var op = ops[opts.op];
if (op == "divide") {
return a.divide(b, 300, bd.RoundingMode.HALF_UP());
} else {
return a[op].call(a, b);
}
}
function multiply(a, b){
return run({"a":a,"b":b,"op":"*"});
}
If you are working with currency (as it seems that you are given the "price" id), you may be better served by using a so called Big Number library (such as this one: https://github.com/iriscouch/bigdecimal.js) for your math to control the math (round up vs round down, etc.). It takes a bit more work to get everything right, but it is worthwhile to avoid the Office Space math scenario.
All javascript number are IEEE-754 double precision floating points numbers. That means that they suffer from round-off errors and imprecision.
All numbers in javascript are floating point numbers, based on IEEE754.
If you want to format one as a string with a fixed number of digits after the dot, use
var formattedNumber = v.toFixed(2); // this makes a string

Multiply numbers with more than 4 decimal points [duplicate]

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

Categories