JQuery Calculation drops cents - javascript

I have this block, that pulls the current amount paid on the item from Firebase and the amount being paid at the moment. Then it is supposed to add the two together to make the third variable.
For some reason the code drops the cents off the total.
singleRef.once("value", function(snapshot) {
var a = parseInt(snapshot.val().amounts.paid); // The amount already paid
var b = parseInt(invoice.payment.amount); // The amount being applied
var c = a + b;
console.log(c);
});
Let's say the following is happening:
a = 0;
b = 10.86;
The result in this code will be:
c = 10; // should be 10.86
Let's say the following is happening:
a = 10.00;
b = 10.86;
The result in this code will be:
c = 20; // should be 20.86
It doesn't matter what the cents are, it always rounds to get rid of them. I've tried adding .toFixed('2') to all of the variables, just a and b, and just c. All result in the same no cent totals.
HOW!? I've been trying to do this for the past few hours, it's probably simple but I can't figure it out. It's driving me nuts! I'm using angularjs and firebase.

The function parseInt() is specifically for parsing integers so, if you give it 3.14159, it will give you back 3.
If you want to parse a floating point value, try parseFloat().
For example, the following code:
var a = parseInt("3.141592653589");
var b = parseInt("2.718281828459");
var c = a + b;
alert(c);
var d = parseFloat("3.141592653589");
var e = parseFloat("2.718281828459");
var f = d + e;
alert(f);
will give you two different outputs:
5
5.859874482047999

As others have mentioned, you can't parse dollars and cents with parseInt().
And using floats is a bad idea for anything financial/monetary.
Most financial systems simply store prices/dollar values in cents, you can write a function to format it nicely for users if there is a need to display the values.
function(cents) {
cents = +cents; // unary plus converts cents into a string
return "$" + cents.substring(0, cents.length - 2) + "." + cents.substring(cents.length - 2);
}

Related

How do you round down to one decimal, even if it ends with a 0 in JavaScript?

I have a product page that is fetching products information and displaying the products on the page. The API returns three price points. I have to add them up and display the price rounded down to one decimal. I have a solution already working, but it only works if it's not a whole number.
22.7312 returns 22.7, but 22.0 returns 22. I would like to always show one decimal, even if it's a zero. This is my current solution. How can I change it so that it shows the one decimal, even if it's a zero?
Math.floor(
(parseFloat(product.price1['regionalPrice'])
+ parseFloat(product.price2['marketPrice'])
+ parseFloat(product.price3['localPrice'])
) * 10) / 10
You need to format your float result with the .toFixed(x) method.
Here is a full code sample for this:
const p1 = parseFloat(product.price1['regionalPrice']);
const p2 = parseFloat(product.price2['marketPrice']);
const p3 = parseFloat(product.price3['localPrice']);
const price = Math.floor((p1 + p2 + p3) * 10) / 10;
const displayPrice = price.toFixed(1);
You could try rounding your numbers with the number.toFixed() function where you pass 1 as a function argument.
I tried it and
num = 22; num = nums.toFixed(1); console.log(num)
prints out 22.0.
Hope that this is what you were looking for ^^

I came up with a way to format numbers to scientific notation, how can I call this function whenever I need it?

I just started learning js and so far am making good progress. I have encountered an issue tho, and the title should basically tell you everything you need to know, but here goes anyways.
For the project I want to realize eventually, I'll need rather big numbers. So I came up with the following to format them to scientific notation:
<script>
var rawNumber = 172 ** 25; // The number that shall be formatted into scientific notation
var exponentDisplay = "e+"; // Self explainatory
var numberRelevantDigits = 0; // The digits displayed before the "e+"
var numberExponent = 0; // Self explainatory
var formattedNumberDisplay = 0; // What will be displayed
function formatNumber() { // The function triggered by clicking the button
var numberExponent = Math.floor( Math.log(rawNumber) / Math.log(10) ); // Calculating the exponent of the number in scientific notation
var numberRelevantDigits = rawNumber / 10 ** numberExponent; // Dividing the number by 10 to the power of its exponent
var numberRelevantDigits = numberRelevantDigits.toFixed(3); // Rounds the relevant digits to 3 decimals
var formattedNumberDisplay = numberRelevantDigits + exponentDisplay + numberExponent; // Adding the relevant digits, "e+" and the exponent into a string
document.getElementById("formattedNumberDisplay").innerHTML = formattedNumberDisplay; // Changing the display to the formatted number
}
</script>
This works as intended, but I don't want to put this chunk of code whenever I need a number formatted. Is there a way (or rather: which is the way) to make it so I can just call that function whenever I need a number formatted? Even if I need use different variables?
Let me apologize again, since this has likely been answered a dozen times before, but I don't even have a clue what to even look for.
Thank y'all in advance.
Create a js file and import it whenever you want
also you should pass the variables to the functions instead of declaring them as a var
inside funciton use const and let, you might some ugly bugs in the future if you don't.
Your file NumberFormater.js will look like:
export formatNumber = (
rawNumber,
exponentDisplay,
numberRelevantDigits,
numberExponent,
formattedNumberDisplay
) => {
let numberExponent = Math.floor( Math.log(rawNumber) / Math.log(10) ); // Calculating the exponent of the number in scientific notation
let numberRelevantDigits = rawNumber / 10 ** numberExponent; // Dividing the number by 10 to the power of its exponent
let numberRelevantDigits = numberRelevantDigits.toFixed(3); // Rounds the relevant digits to 3 decimals
let formattedNumberDisplay = numberRelevantDigits + exponentDisplay + numberExponent; // Adding the relevant digits, "e+" and the exponent into a string
document.getElementById("formattedNumberDisplay").innerHTML = formattedNumberDisplay; // Changing the display to the formatted number
}
then when needed:
import { formatNumber } from './NumberFormater.js';
const rawNumber = 172 ** 25; // The number that shall be formatted into scientific notation
const exponentDisplay = "e+"; // Self explainatory
const numberRelevantDigits = 0; // The digits displayed before the "e+"
const numberExponent = 0; // Self explainatory
const formattedNumberDisplay = 0; // What will be displayed
formatNumber( rawNumber, exponentDisplay, numberRelevantDigits, numberExponent, formattedNumberDisplay);
read more on js modules https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
Hope I've helped.

How to format numeric values with pattern?

I'm finding an equivalent to Java's DecimalFormat in JavaScript. I would like to format given numeric values with given decimal pattern like
"#,###.00"
"###.##"
"#,###.##"
"$#,##0.00"
"###,###.00"
"$###,###.00"
"###,###.###"
"####,####.000"
Has there any way to achieve it?
Part 1 - formatting
I would recommend using the Intl.NumberFormat natively supported in javascript, although it may not be supported by older browsers. Looks like IE11 has it, but not android.
So if you wanted to support US Dollars you would simply use something like this
var dollarFormat = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
var amountInDollars = dollarFormat.format(123456.123);
// amountInDollars = "$123,456.12"
But this also rounds up for you, for example
var roundedDollars = dollarFormat.format(555.555);
// roundedDollars = "$555.56";
For the numeric cases just use a different formatter. The default 'en-US' adds commas, a decimal before fractional numbers, and limits to 3 fractional numbers. But this is configurable.
var numberFormat = new Intl.NumberFormat('en-US');
var formatted = numberFormat.format(123456.123456);
// formatted = "123,456.123"
var numberFormat2decimals = new Intl.NumberFormat('en-US', { maximumFractionDigits: 2 });
var formatted2 = numberFormat2decimals.format(123456.123456);
// formatted2 = "123,456.12"
You can set maximum and minimum for fraction, integer, and significant digits, and this also supports international formats. Since it's native javascript, I think it's a good way to go if your platforms support it.
MDN is an excellent reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
Part 2 - the 0's
To achieve the 0's in your formats you'll have to modify the value before passing to the formatter. If you require a minimum fractional amount, you're fine for things like .00, the currency formatter will do that by default. If you've got fractal numbers you don't want, just use Math.trun() to truncate the values.
var num = Math.trun(1234.1234);
// num = 1234
Now to change something like 12345 to 12340 we'll have to remove some of the numeric value. We can find out much by converting to a string, pulling the last character, and converting back.
var num = 123456.12345;
var wholeNum = Math.trunc(num);
// wholeNum = 123456;
var toRemove = Number.parseInt(wholeNum.toString().slice(-1), 10);
// toRemove = 6
// slice(-1) gives us the right-most character of a string.
// Notice the ', 10' at the end, this is important to indicate which number base to use for parseInt.
var wholeNumEnding0 = wholeNum - toRemove;
// wholeNumEnding0 = 123450
Hopefully that's what you're looking to accomplish? I didn't perform any rounding here.
Note: I typed this at speed, excuse any mistakes, there might be better ways to do it too.
If you don't want to rely on a library, you could do something like the following:
var number = 100000.00000000000012422;
function FormatNumber(no){
no = no.toFixed(2);
no = no.toString().split('.');
var p1 = no[0];
p1 = p1.substring(0, p1.length - 3) + ',' + p1.substring(p1.length - 3);
no = p1 + '.' + no[1];
console.log(no);
}
FormatNumber(number);
The FormatNumber function takes a number as a parameter (you would probably want to expand that to include e.g. decimal places). It converts the number to the required decimal places, the turns it into a string and splits it by the decimal separator '.'.
The next step is to add a thousands separator three characters from the back, then it's just a matter of joining the remaining characters back together.
JSFiddle
If you wanted to get a ',' every 3 characters you could write a little more 'complex' formatter, something along the lines of the following:
no = no.toFixed(2);
no = no.toString().split('.');
var p1 = no[0];
var arr = [];
arr = p1.split("").reverse().join("").match(/[\s\S]{1,3}/g) || [];
arr = arr.reverse();
p1 = "";
for(var i = 0; i < arr.length; i++){
p1 += arr[i].split("").reverse().join("");
if(i != arr.length - 1){
p1 += ',';
}
}
no = p1 + '.' + no[1];
This method splits the number into an array by each number, reverses the array as we need to start from the end of the string to get accurate result.
Then we iterate the array of strings with 3 or less values by splitting the number into an array again, reversing it and joining back together and then appending to p1. If it's the last item, it doesn't add a comma.
Lastly we take the decimal and append to built string.
JSFiddle

How would I write this formula in Javascript?

I have a project I am working on and it needs to calculate mortgage calculations but I'm having trouble putting the formula into javascript.
the formula is:
M = P I(1 + I)^n /(1 + I )^n - 1
Any help is appreciated, thanks
P = loan princible
I = interest
N = Term
Break it down into a sequence of steps.
Multiplication is as straightforward as it gets: I*(1+I)
Division is the same: I/(1+I)
To the power of n is denoted by: Math.pow(3, 5); //3 to the power of 5
Math.pow() might be the only thing you didn't know yet.
Unrelated but useful,
Wrap your formula into a function and you have a mortgage-calculation function
calculateMortgage(p,i,n) {
result = //translate the formula in the way I indicated above
return result;
}
and call it like so:
var mortgage = calculateMortgage(300,3,2); // 'mortgage' variable will now hold the mortgage for L=300, I=3, N=2
Also, the formula you posted really doesn't make any sense - why is there a blank between P & I at the very beginning? Something's missing.
Try this: Math.pow(p*i*(1+i),n)/Math.pow(1+i,n-1)
Math.pow(a,2) is same as a^2
if P is not supposed to be with numerator then
this
p * (Math.pow(i*(1+i),n)/Math.pow(1+i,n-1))
or
p * (Math.pow((i+i*i),n)/Math.pow(1+i,n-1))
var M;
var P;
var I;
M = P*(Math.pow(I*(1+I),n)) / (Math.pow((1+I),n)-1);
Does this look right to you? I got the correctly styled formula from here.
Like what Nicholas above said, you can use functions to make it all the more easier.
var M;
function calculateMortgage(P, I, N){
M = P*(Math.pow(I*(1+I),n)) / (Math.pow((1+I),n)-1);
alert("Your mortgage is" + M);
}
And just call calculateMortgage(100, 100, 100); with your values for it to automatically give the answer to you.

JS Vars - Adding

I have two variables, 'a' and 'b' in my JavaScript, and i want to add them together - i assume this code:
var a = 10;
var b = 30
var varible = a + b;
This, puts the two numbers next to each other... any ideas why... the result should be 40?
You probably have strings instead of integers. That is your code really is like this:
var a = "10";
var b = "30";
var c = a + b; // "1030"
There are several ways to convert the strings to integers:
a = parseInt(a, 10); // Parse the string
b = b * 1; // Force interpretation as number
new is a reserved word, I'd use something else in any case.
And with a normal variable name of c it worked for me:
var a = 10;
var b = 30
var c = a + b;
alert(c);
did the expected and alerted 40
new is a keyword in JavaScript. you should not use it to declare your variables or functions. change the variable name from new to something else
Are you sure you didn't do this:
var a = '30';
var b = '40';
Here, I show '30' as a string rather than a number, and I would expect the "+" operator to concatenate two strings. Since this is contrived code, you may not be entirely sure where your variables were initially assign or what type they have. You can check it like this:
var a = '30';
var b = '40';
alert( typeof(a) + '\n' + typeof(b) );
If either of those say 'object' or 'string' rather than 'number' this is your problem. One way this might happen that you didn't expect is with an input. Say you have code like this:
<input id="a" value="30" />
<input id="b" value="40" />
<script language="javascript">
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
</script>
Here, the value of a text input is always a string initially.
If you want to convert a variable to a number first you should use something like myVar - 0 to coerce a numeric operation or the more-formal parseInt() or parseFloat() functions (don't forget the radix parameter for parseInt()). And always check isNaN() on the results.
I'm really surprised that noone has until now suggested the obvious: "Casting" with JavaScript (I set it in quotes, because it is no real casting).
var a = "1"; // string
var b = Number(a); // number
var c = String (b); // string again
a + b; // "11"
b + a; // 2
a + c; // "11"
Now, why is this no real casting? Because you don't create a new variable of type "number" but a new object "Number" and initialize it with something that could be numerical.
One or both is a string. If you get the values from a HTML input or something, they definitely are. Make sure they're both integers by using parseInt:
var newValue = parseInt(a,10) + parseInt(b,10);
Also, 'new' is a keyword. You can't use that for a variable name :)

Categories