JQuery not showing correct decimal output - javascript

My problem with this is, everything is fine up to two decimal places when its preceded 1-9, however if the number is a 10th, then my script will only show to one decimal place.
E.g 200.19, 5000.42, 12.98 << will be fine however if the output should be 123.10 it will display 123.1
Here's my code:
jQuery(document).ready(function() {
function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n= yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return n.join(".");
}
function loanCalc() {
//Get the parameter from the form
var rate=jQuery('#start_rate').val();
var priceValue=jQuery('#input_1_2').val();
console.log("price value before"+priceValue);
if(priceValue.indexOf('£') == 0) {
var strEnd=jQuery('#input_1_2').val().indexOf(',') - 1;
priceValue=parseInt(priceValue.substr(1,priceValue.strEnd))*1000;
}else{
priceValue=priceValue;
}
var princ = parseInt(priceValue);
var term = parseInt(jQuery('#input_1_3').val());
var intr = rate / 1200;
console.log("price"+priceValue+" term"+term+" rate"+rate);
var calculation = princ * intr / (1 - (Math.pow(1/(1 + intr), term)));
console.log("paymenet"+calculation);
var rePayment= calculation*term;
var costOfCredit=princ-rePayment;
//set the value
jQuery('#figure').html('£'+ ReplaceNumberWithCommas(calculation.toFixed(2)));
jQuery('#rate').html(rate+"%");
jQuery('#total').html('£' +
ReplaceNumberWithCommas(rePayment.toFixed(2)));
jQuery('#credit').html('£' + ReplaceNumberWithCommas(
Math.abs(costOfCredit.toFixed(2 ))));
As you can probably guess, there are 3 fields that I am displaying, the calculation, which is a percentage, 'rePayment' and 'costOfCredit'. The weird thing is 'rePayment' works fine and has no problem showing the 2nd decimal place even if its a 10th/ends with zero.
So my question is can you guys help me find what my problem is with getting the 2nd decimal place to show is?

When you call Math.abs(), it's converting the string with 2 digits after the decimal back to a number, which loses the trailing zeroes. You should call Math.abs() first, then call toFixed() on this to add the trailing zeroes.
jQuery('#credit').html('£' +
ReplaceNumberWithCommas(Math.abs(costOfCredit).toFixed(2)));

Related

Regarding decimal in javascript

When i am writing 11.00 it is displaying 11.00.00 otherwise its working fine on rest
if(pos == -1)
{
document.getElementById("printCheckAmount").textContent = "$" + checkObj.checkAmount + ".00";
}
else
{
var integer = enterCheckAmount.substring(0,pos);
var decimals = enterCheckAmount.substring(pos+1);
while(decimals.length<2) decimals=decimals+'0';
enterCheckAmount = integer + '.' + decimals;
document.getElementById("printCheckAmount").textContent = "$" + checkObj.checkAmount;
}
JavaScript doesn't have a variable type for decimal numbers. It has only Number. If you want to display an integer as a decimal number with two zeros after the decimal point you can use the method toFixed.
Here is an example:
var myNumber = 11;
var myDecimalNumber = myNumber.toFixed(2);
console.log(myDecimalNumber) // will output 11.00
Thus there is no need to concatenate strings and add ".00" manually to your number.
Beyond this you can use the methods parseInt and parseFloat. Let's say you have a variable of type string with the value "11 pieces". You can get the integer with this line of code:
var myString = "11 pieces";
var myInteger = parseInt(myString, 10);
console.log(myInteger); // will output 11
If you have something similar like this, you are better off with this methods instead of cuting substrings.
I wish you a lot of success in refactoring your code and a warm welcome to the StackOverflow community.

toFixed Isn't Doing Anything

I'm teaching myself JavaScript and have run into a problem with toFixed(). I'm working through an amortization calculator; and, one of the steps returns a number with a huge number of decimal places. I'm trying to cut it down to 4 decimal places.
Be advised the sample code has a lot of explanatory HTML in it. It's only there so that I can work through the steps of the equation. Also, when I add one to the very long number, it adds the numeral one to end of the scientific notation.
var paymentamount;
var principal=250000;
var interestrate = 4.5;
var annualrate = interestrate/12;
var numberofpayments = 360;
document.write("This is the annuitized interest rate: "+ annualrate +"%");
document.write("<h3> Now we add 1 to the annualized interest rate</h3>");
var RplusOne = annualrate + 1;
document.write("<p> This is One Added to R: " + RplusOne + "%");
document.write("<h3>Next RplusOne is Raised to the power of N </h3>");
var RRaised = (Math.pow(RplusOne, numberofpayments)).toFixed(4);
document.write("<p>This gives us the following very long number, even thought it shouldn't: " + RRaised);
document.write("<h3>Now we add one to the very long number </h3>");
var RplusOne = RRaised + 1;
document.write("<p>Now we've added one: " + RplusOne);
From MDN's documentation:
If number is greater than 1e+21, this method simply calls Number.prototype.toString() and returns a string in exponential notation.
The problem is that you are using 4.5 as your interest rate instead of 0.045, so doing this:
Math.pow(4.5 / 12 + 1, 360)
gives you a huge number (6.151362770461608e+49 or 6.15 * 10^49 to be exact). Change your interest rate to 0.045 and you will get what you are expecting.
As for the var RplusOne = RRaised + 1 line, the problem here is that RRaised is a string because of toFixed. I would only call toFixed when you're displaying things, and not at any other time; the primary reason for this would be to avoid rounding errors in subsequent calculations, but has the added benefit that your variables remain numbers and not strings.

Javascript: Convert a string representation of money to Number

Lets say I have an amount in string format like this:
amount = '12,000.00'
I want to convert it into a Number (Javascript) or a float.
parseFloat(amount) // this gives me 12 as a result
Number(amount) // this gives me NaN as a result
Other solution I thought was this:
parseFloat(amount.replace(/[,]/g, ''))
This works fine. But the problem here is the Locale.
This would fail when the amount is € 12000,00.
Here ',' has altogether a different meaning.
I looked around for a good solution but couldn't. I am looking for a generalized solution.
This is not that easy, as you can't exactly know what's the delimiter for thousands and what for the decimal part
Consider "12.000.000" is it 12000.000 === 12000 or 12000000?
But if you would set the requirement that the last delimiter is always the decimal delimiter -
meaning if at least one delimiter is given, the last one has to be the decimal delimiter, *if the digits following, don't exceed a defined length.
Then you could try the following
Edit
(see the revs if you're interested in the old function)
I put in the ability to define the max length of digits after the last delimiter "," or "." up until it is treated as float, after that its returned as integer
var amounts = ["12000","12.000,00", "12,000.00", "12,000,01", "12.000.02", "12,000,001"];
formatMoney.maxDecLength = 3; //Set to Infinity o.s. to disable it
function formatMoney(a) {
var nums = a.split(/[,\.]/);
var ret = [nums.slice(0, nums.length - 1).join("")];
if (nums.length < 2) return +nums[0];
ret.push(nums[nums.length - 1]);
return +(ret.join(nums[nums.length - 1].length < formatMoney.maxDecLength ? "." : ""));
}
for ( var i=0,j;j=amounts[i];i++)
console.log (j + " -> " +formatMoney(j));
Gives the output:
"12000 -> 12000"
"12.000,00 -> 12000"
"12,000.00 -> 12000"
"12,000,01 -> 12000.01"
"12.000.02 -> 12000.02"
"12,000,001 -> 12000001" //as you can see after the last "," there are 3 digits and its treated as integer
Another JSBin
You can get the local decimal delimiter in this manner:
1.1.toLocaleString().substr(1,1)
Before parse float, you could make sure the string contains nothing but numbers, possibly a minus sign, and the local decimal delimiter.
The truth is, you'll never know the format. 12,345. Is that 12345, or another locale version if 12.345?
However, if you have consistent decimals, then you'd be able to use the lastIndexOf function on a comma and a period will reveal the decimal position and character.
var price = '12,345.67';
var lastPeriod = price.lastIndexOf('.');
var lastComma = price.lastIndexOf(',');
if (lastComma != -1 && lastComma > lastPeriod) {
decimalCharacter = ',';
} else {
decimalCharacter = '.';
}
console.log(decimalCharacter); //. or , based on how the price string looks - see below
If price is 12,345.67, decimalCharacter will be .. If it's 12.345,67, it'll be returned as ,.

JavaScript function to add two numbers is not working right

My code in HTML takes a user input number in, and it does a calculation and then displays the output. The user chosen input is put into a formula and the result of the formula is added to the user input number, but when it adds the two number together it's adding a decimal spot.
For example, if the number 11 is chosen, the result of Rchange is 0.22, so .22 is then added 11 to be 11.22 for newResistance, but instead it is displaying the value as 110.22 instead.
function calc(form) {
if (isNaN(form.resistance.value)) {
alert("Error in input");
return false;
}
if (form.resistance.value.length > 32) {
alert("Error in input");
return false;
}
var Rchange = .01 * 2 * form.resistance.value;
var newResistance = (form.resistance.value + Rchange);
document.getElementById("newResistance").innerHTML = chopTo4(newResistance);
}
function chopTo4(raw) {
strRaw = raw.toString();
if (strRaw.length - strRaw.indexOf("0") > 4) strRaw = strRaw.substring(0, strRaw.indexOf("0") + 5);
return strRaw;
}
HTML DOM element properties are always strings. You need to convert them to numbers in your usage.
parseInt(form.resistance.value);
parseFloat(form.resistance.value);
+form.resistance.value;
(Any of the three will work; I prefer the first two (use parseInt unless you're looking for a float).)
Try newResistance = +form.resistance.value + Rchange;. This will convert it to a number.
It's because it's treating the values as a string.
form.resistance.value + Rchange are both strings, so it's appending it.
Use the parseInt JavaScript method to get the decimal version.

How to append an extra 'Zero' after decimal in Javascript

Hye,
Iam new to javascript working with one textbox validation for decimal numbers . Example format should be 66,00 .but if user type 66,0 and dont type two zero after comma then after leaving text box it should automatically append to it .so that it would be correct format of it . How can i get this .How can i append ?? here is my code snippet.
function check2(sender){
var error = false;
var regex = '^[0-9][0-9],[0-9][0-9]$';
var v = $(sender).val();
var index = v.indexOf(',');
var characterToTest = v.charAt(index + 1);
var nextCharAfterComma = v.charAt(index + 2);
if (characterToTest == '0') {
//here need to add
}
}
Use .toFixed(2)
Read this article: http://www.javascriptkit.com/javatutors/formatnumber.shtml
|EDIT| This will also fix the issue if a user types in too many decimals. Better to do it this way, rather than having a if to check each digit after the comma.
.toFixed() converts a number to string and if you try to convert it to a float like 10.00
then it is impossible.
Example-
10.toFixed(2) // "10.00" string
parseFloat("10.00") // 10
Number("10.00") // 10

Categories

Resources