js function ignores Decimal Numbers - javascript

So i made a function that calculate the price by multiplication how many meters i put the problem is when ever i put decimal numbers it ignores it
heres my script
<script>
function getFillingPrice() {
cake_prices = document.getElementById('price').value;
filling_prices = document.getElementById('test2').value;
var t=parseInt(filling_prices);
var x=parseInt(cake_prices);
return t*x;
}
function calculateTotal() {
var total = getFillingPrice();
var totalEl = document.getElementById('totalPrice');
document.getElementById('test3').value =total + " دينار ";
totalEl.style.display = 'block';
}
</script>

You're converting the values to integers when you get them from the DOM.
Change this...
var t=parseInt(filling_prices);
var x=parseInt(cake_prices);
to this...
var t=parseFloat(filling_prices);
var x=parseFloat(cake_prices);

Beside the parsing problem, you could use
an unary plus + and
a default value for non parsable value, like letters or an empty string (falsy values) with a logical OR ||.
cake_price = +document.getElementById('price').value || 0
// ^ unary plus for converting to numbner
// ^^^ default value for falsy values
Together
function getFillingPrice() {
var cake_price = +document.getElementById('price').value || 0,
filling_price = +document.getElementById('test2').value || 0;
return cake_price * filling_price;
}

Related

thousand and decimal separate in key up event

I used below code to thousand and decimal separate in key up event. But after entering 15 digits value gets 0. what will be the reason ??
<script>
var myinput = document.getElementById('myinput');
myinput.addEventListener('keyup', function() {
var val = this.value;
val = val.replace(/[^0-9\.]/g,'');
if(val != "") {
valArr = val.split('.');
valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
val = valArr.join('.');
}
this.value = val;
});
</script>
<input id="myinput" type="text'>
Problem:
The problem here is that you reached the maximum possible value for Number on parseInt() when it tries to parse the input string value, check the Number.MAX_SAFE_INTEGER MDN Reference for further details.
So all the extra digits you enter, when the number exceeds the Number.MAX_SAFE_INTEGER, will be ignored and transformed to 0. Please check Working with large integers in JavaScript tutorial for more explanation and examples.
So, you can't treat a large number value as a Number in Javsacript because there's a Maximum possible value limit, you need to treat it as a string, so it can exceed this max value.
Solution:
The solution here is to treat this number as a string and use Regex and .replace() method to change its format.
Here's a solution that I wrote before and that I always use to format numbers, it will solve your problem:
var formatNumber = function(input, fractionSeparator, thousandsSeparator, fractionSize) {
fractionSeparator = fractionSeparator || '.';
thousandsSeparator = thousandsSeparator || ',';
fractionSize = fractionSize || 3;
var output = '',
parts = [];
input = input.toString();
parts = input.split(".");
output = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator).trim();
if (parts.length > 1) {
output += fractionSeparator;
output += parts[1].substring(0, fractionSize);
}
return output;
};
Demo:
This is a working Fiddle with your original code.

Using arrays to do basic calculations with negative exponent

I'm trying to write a function which outputs the correct result when multiplying a number by a negative power of ten using arrays and split() method. For example the following expressions get the right result: 1x10^-2 = 0.01 1x10^-4 = 0.0001.
Problem comes when the number's length is superior to the exponent value (note that my code treats num as a string to split it in an array as shown in code bellow :
//var num is treated as a string to be splited inside get_results() function
//exponent is a number
//Try different values for exponent and different lengths for num to reproduce the problem
//for example var num = 1234 and var exponent = 2 will output 1.234 instead of 12.34
var num = '1';
var sign = '-';
var exponent = 2;
var op = 'x10^'+sign+exponent;
var re = get_result(num);
console.log(num+op +' = '+ re);
function get_result(thisNum) {
if (sign == '-') {
var arr = [];
var splitNum = thisNum.split('');
for (var i = 0; i <= exponent-splitNum.length; i++) {
arr.push('0');
}
for (var j = 0; j < splitNum.length; j++) {
arr.push(splitNum[j]);
}
if (exponent > 0) {
arr.splice(1, 0, '.');
}
arr.join('');
}
return arr.join('');
}
Demo here : https://jsfiddle.net/Hal_9100/c7nobmnj/
I tried different approaches to get the right results with different num lengths and exponent values, but nothing I came with worked and I came to the point where I can't think of anything else.
You can see my latest try here : https://jsfiddle.net/Hal_9100/vq1hrru5/
Any idea how I could solve this problem ?
PS: I know most of the rounding errors due to javascript floating point conversion are pretty harmless and can be fixed using toFixed(n) or by using specialized third-party librairies, but my only goal here is to get better at writing pure javascript functions.
I am not sure if you want to keep going with the array approach to a solution, but it seems like this could be solved with using the Math.pow() method that already exists.
function computeExponentExpression ( test ) {
var base;
var multiplier;
var exponent;
test.replace(/^(\d+)(x)(\d+)([^])([-]?\d+)$/, function() {
base = parseInt(arguments[1], 10);
multiplier = parseInt(arguments[3], 10);
exponent = parseInt(arguments[5], 10);
return '';
} );
console.log( base * Math.pow(multiplier, exponent));
}
computeExponentExpression('1x10^-4');
computeExponentExpression('1x10^2');
computeExponentExpression('4x5^3');
The problem is where you push the decimal point .
instead of
arr.splice(1, 0, '.');
try this:
arr.splice(-exponent, 0, '.');
See fiddle: https://jsfiddle.net/free_soul/c7nobmnj/1/

Move comma position JavaScript

I'm trying to move the position of the comma with the use of JavaScript. I have managed to remove all the parts of the string I needed removing. The only problem is that the comma is in the wrong position.
The current outcome is 425.00, but I simply want '42.50'
success: function(result) {
if (result != '') {
alert(" "+result+" ");
}
var discountVal = result.replace(/\D/g,'');
newDiscountVal = discountVal.replace(7.50, '');
$("input#amount").val(discountVal);
}
I am grabbing database echo values with a combination of string and echo - numbers..
You could divide by ten, then convert back to a String using toFixed(2) which forces formatting of 2 decimal places
Javascript allows implicit conversion of Strings to numbers, by firstly converting the String to a Number so it is valid to divide a String by a number.
var input= "4250.00";
var output = (original / 100).toFixed(2); // => "42.50"
Note this method has different behaviour due to rounding. Consider the case 9.99. If you use a string manipulation technique you'll get ".99", with divide by 10 method above you'll get "1.00". However from what has been said in comments I believe your inputs always end .00 and never anything else, so there will be no difference in reality.
If it is number you can just divide by 10
If it is string you can do like this:
var ind = text.indexOf('.');
text = text.replace('.', '');
text.slice(0, ind-1) + '.' + text.slice(ind-1, text.length)
Here is a solution:
function moveComma(val, moveCommaByInput) {
if (val || typeof val === 'number') {
const valueNumber = Number(val);
const moveCommaBy = moveCommaByInput || 0;
if (isNaN(valueNumber)) {
return null;
} else {
return Number(`${valueNumber}e${moveCommaBy}`);
}
}
return null;
}
This is how i solved it..
var discountVal = result.replace(/\D/g, '');
var newDiscountVal = discountVal.replace(7.50, '');
var lastDigits = newDiscountVal.substr(newDiscountVal.length - 2);
var removedDigits = newDiscountVal.slice(0,newDiscountVal.length - 2);
var discountRealValue = removedDigits + '.' + lastDigits;
$("input#amount").val(discountRealValue);
Cheers

How to sum 2 numbers witout rounding

I have 2 numbers
a = 1548764548675465486;
b = 4535154875433545787;
when I sum these number they are rounded to
a => 1548764548675465500
b => 4535154875433545700
and a + b returns 6083919424109011000 while it should return 6083919424109011273
is there a javascript solution to solve this problem witout the use of a library ?
To work around the precision limitations associated with JavaScript's numbers, you will need to use a BigInteger library like the popular one offered here: http://silentmatt.com/biginteger/
Usage:
var a = BigInteger("1548764548675465486");
var b = BigInteger("4535154875433545787");
var c = a.add(b);
alert(a.toString() + ' + ' + b.toString() + ' = ' + c.toString());
// Alerts "1548764548675465486 + 4535154875433545787 = 6083919424109011273"
Demo: http://jsfiddle.net/69AEg/1/
There are no integers in Javascript, all numbers are double precision floating point.
That gives you a precision of around 15-16 digits, which is what you are seeing.
as per this question
and potential solution i.e. use a library
Personally, I would not use javascript, never been great at numbers. Just try typing 0.1 + 0.2 into any browsers console window. Result is 0.30000000000000004.
Send the calculation to your server side language (as a string) and do the work there, you should have a better outcome.
Technical article on the nuances of floating point numbers here, if you interested
Well, here is a solution I found witout the use of any external library, all I need to do is to define a class that had a property value wich should be a string, and define the function plus
function LongNumber()
{
// it takes the argument and remove first zeros
this.value = arguments[0].toString();
while(this.value[0]==="0")
this.value = this.value.substr(1);
// this function adds the numbers as string to another string and returns result as LongNumber
this.plus = function (Num)
{
var num1 = pad(Num.value.length, this.value);
var num2 = pad(this.value.length, Num.value);
var numIndex = num1.length;
var rest = 0;
var resultString = "";
while (numIndex)
{
var number1 = parseInt(num1[(numIndex)-1]);
var number2 = parseInt(num2[(numIndex--)-1]);
var addition = (number1+number2+rest)%10;
rest = parseInt((number1+number2+rest)/10);
resultString = addition.toString() + resultString;
}
return new LongNumber((rest?rest.toString():"") + resultString);
}
function pad(width, string)
{
return (width <= string.length) ? string : pad(width, '0' + string)
}
}
All i need to do now is to declare 2 LongNombers and use the function plus
var Number1 = new LongNumber("1548764548675465486");
var Number2 = new LongNumber("4535154875433545787");
var Result = Number1.plus(Number2);
Result.value // returns "6083919424109011273"

Javascript: why does this produce and ugly string??? I would like currency

var total = 0;
$(".amount").each(function () {
var value = $(this).val();
value = (value.length < 1) ? 0 : value;
var tmp = parseFloat(value).toFixed(2);
total += tmp;
});
$(".total").text(total);
I am trying to loop through some text boxes and sum up their values. This produces a nasty string. What am I missing?? if I put 8 in the first textbox total text ends up as " 08.000.000.000.00". What am I doing wrong? I would like to format as currency but if not, at least just a two decimal number. Any pointers?
.toFixed converts the object from a Number to a String.
Leave the full values in place and only convert using .toFixed at the very end
$(".total").text(total.toFixed(2));
Alternatively, convert the string back to a number.
total = total + + tmp;
Just FYI, there is an excellent mathematical aggregation plugin for jQuery: jQuery Calculation
Using that plugin may also indirectly solve your issue.
It's usage would reduce your script to:
$('.total').text($('.amount').sum());
You are converting the parseFloat into a string, then adding it to total. Only add .toFixed(2) to the final line, once things have been added.
var total = 0;
$(".amount").each(function() {
var value = $(this).val();
value = (value.length < 1) ? 0 : value;
var tmp = parseFloat(value);
total += tmp;
});
$(".total").text(total).toFixed(2);

Categories