Regarding decimal in javascript - 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.

Related

Sum of toFixed not working correctly

I have the following code that calculates and shows the sum of two values.
var oldprice_formated = parseFloat(oldprice).toFixed(2);
var extraPrice = parseFloat(3).toFixed(2);
if(initials != '') {
var new_price = oldprice_formated + extraPrice;
$('.product-detail .woocommerce-Price-amount.amount').html('<span>€</span>'+new_price);
} else {
$('.product-detail .woocommerce-Price amount.amount').html('<span>€</span>'+oldprice_formated);
}
For example:
oldprice_formated = parseFloat(49.99).toFixed(2);
extraPrice = parseFloat(3.00).toFixed(2)
The expected result: Sum is 52.99
Actual result: Sum is 49.003.00
What am I doing wrong? I assume it's with the number parsing, but not sure what I should change to make it work correctly. Thanks!
.toFixed() returns a string, not a number with only two decimal places.
oldprice_formated = parseFloat(49.99).toFixed(2); // "49.99"
extraPrice = parseFloat(3.00).toFixed(2); // "3.00"
When adding those two variables, instead of a number sum, you're concatenating two strings:
"49.99" + "3.00"; // "49.993.00"
I believe this is what you'll want to do:
var new_price = parseFloat(oldprice_formated) + parseFloat(extraPrice);
Or simply run .toFixed() after you sum those values which were already parsed to floats.
Because toFixed() returns a string, the + operator acts as a string concatenator. If you want it to operate as an addition operator, you must typecast your values as numbers:
let oldprice = 49.99;
let oldprice_formatted = parseFloat(oldprice).toFixed(2);
let extraPrice = parseFloat(3).toFixed(2);
console.log(`string concatenation: ${oldprice_formatted + extraPrice}`)
console.log(`type conversion: ${+oldprice_formatted + +extraPrice}`)

Javascript: how to get micronumbers in decimal format

I have simple function that calculates number of decimals,
eg. _d(0.01) = 2, _d(0.001) = 3 and so on.
We added some new coins to our system that have 0.00000001 quantity and function broke.
Here is why:
0.00000001.toString() = 1e-8, so I cant split it it by '.' and calculate length of second part as I did before.
So the question is - how to get string '0.00000001' out of 0.00000001 number easiest way.
EDIT
I didnt mean exactly '0.00000001', I meant any micronumber to decimal without exp. Some function _d(x) that would work _d(0.000000000012) = '0.000000000012'and so on. What usually toString() does to large (but not too large) numbers.
Use toFixed() with a large number of digits, then count the number of zeroes after the decimal point.
function _d(num) {
var str = num.toFixed(100);
var fraction = str.split('.')[1];
var zeros = fraction.match(/^0*/)[0].length;
return zeros + 1;
}
console.log(_d(0.1));
console.log(_d(0.01));
console.log(_d(0.000000001));
Do you want some thing like this
function decimalPlaces(num) {
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(
0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0)
// Adjust for scientific notation.
- (match[2] ? +match[2] : 0));
}
console.log(decimalPlaces(0.000000001))
First off, I got some inspiration for this answer from here:
How to avoid scientific notation for large numbers in JavaScript?
You can convert the number to a strong and then check for str.indexOf("e"). If true, then just return the scientific notation part of the string. For example:
function _d() {
// your current function here
if (str.indexOf("e")) {
var something = str.split("-")[1];
return something;
}
}
EDIT: I was working on this before your last comment to me, so this returns a string of the number, which I thought was what you wanted.
Leaving aside the point about significant digits, which is meaningful and correct but does not solve your problem, try this. We take the number, convert to string, if that string is not scientific notation then the answer is trivial. If it is scientific notation, then split the string twice (once on "e-" and then split the zeroth array on "." Add str[1]-1 zeroes to the lead of the number and add the digits to the end.
function _d(arg) {
var str = arg.toString();
if (str.indexOf("e-")) {
var digits = str.split("e-")[0];
var zeroes = str.split("e-")[1];
var zero = Number(zeroes);
var each = digits.split(".");
var something = "0.";
for (var i = 0; i < zeroes-1; i++) {
something += "0";
}
for (var j = 0; j < each.length; j++) {
something = something + each[j];
}
return something;
}
}
This won't work with very large numbers or very small negative numbers. And its pretty convoluted.
The other way is to use .toString() and then look for .length-2(2 characters - '0.'. It should give you the number of zeros.
The advantage of this method is you don't need to know the number of maximum decimals in the number.
To keep it as the full decimal:
Number(0.000001)
// 0.000001
To show it as a string:
0.000001.toFixed(6)
// "0.000001"

JQuery not showing correct decimal output

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)));

get wrong result function jquery javascript

I am using the following script. But I am receiving a wrong result for x_b_bbetrag.
When do an calculation exp 100/108 I get 9.92 instead of 92.59.
What am I missing here?
Code below:
var betrag = 100
var kurs = 1
var minkl= 1
var msatz= 0.08
$("#x_b_betrag").change(function() {
var betrag = $("#x_b_betrag").val();
var kurs = $("#x_b_kurs").val();
var minkl =$("input[name='x_b_mwstinkl']:checked").val();
var msatz =$("input[name='x_b_mwst']:checked").val();
if (minkl == "1"){
$("#x_b_rechenbetrag").val((betrag * kurs).toFixed(2));
$("#x_b_bbetrag").val( ( (betrag * kurs) /(1 + msatz) ).toFixed(2));
}
Use parseFloat
multiplication, division and subtraction automatically parse string to number. for summation you need to parse it.
$("#x_b_bbetrag").val( ( (betrag * kurs) /(1 + parseFloat(msatz) ) ).toFixed(2));
///1 + "1" = 11 not 2
Parse your inputs into numbers.
For example :
var betrag = parseFloat($("#x_b_betrag").val());
MDN on parseFloat
The value of the msatz variable is not 0.08 but "0.08". It's a string, so when you add one to it, the number will be converted to a string so that they can be concatenated, and the result is "10.08" not 1.08. The string will implicitly be converted to a number when you use it in the division, as it's not possible to divide by a string.
Parse the string into a number:
var msatz = parseFloat($("input[name='x_b_mwst']:checked").val());

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 ,.

Categories

Resources