Javascript: using toLocaleString + Tofixed - javascript

I need to format a number for a project im working on at work, only problem is that I cant format it how i want.
I convert the number to a localestring using the toLocaleString method which gives me the commas but i also need decimal places, nothing i seem to do works.
var number = 123.322
number = parseFloat(number).toFixed(2) //123.22
number.toLocaleString() //123.22
The above code just returns the parsefloated number along with the tofixed decimal values but it doesn't add the commas.
How do i get a number to have two decimal places (when the value is 'xx.00') and also be comma separated. Is this possible in JavaScript?

You can give an object to .toLocaleString() which describes what you want:
var sNumber = (10123.322).toLocaleString(undefined,
{'minimumFractionDigits':2,'maximumFractionDigits':2});
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
Original:
const fNumber = 10123.322;
const sNumber = parseFloat(fNumber.toFixed(2)).toLocaleString();
console.log(sNumber);
The number is already in decimal/float format on the first line.
.toFixed(2) turns it into a string using fixed-point notation.
parseFloat() takes that string and turns it back into a float.
.toLocaleString() turns it into a string using the local format.

Just to do it in one line
var num = '12233.3366554';
num = parseFloat(parseFloat(num).toFixed(2)).toLocaleString('en-IN', { useGrouping: true });

Yes, it is possible using .toLocaleString, yo just need to specify the language, optionally you can specify decimals and currency. look at this example:
35000.2455.toLocaleString('en-IN', {minimumFractionDigits: 2, maximumFractionDigits: 2,style: 'currency', currency: 'USD' })
this returns $35,000.25

Number.toLocaleString works on a number, but toFixed returns a string.
Coerce the string back into a number first
var number = 123.322;
var string = parseFloat(number).toFixed(2);
var parsed = (+string).toLocaleString();
console.log(parsed);

In order to get commas you have to specify the locale .The locale en includes commas for the numbers. toFixed() Returns a string. toLocaleString() function commas works on a number not on a string.So parse the string to float.
var number = 1234567.322;
number = parseFloat(parseFloat(number).toFixed(2)).toFixed(2) ;
number=number.toLocaleString('en');

toLocaleString function provide number representation based on languages
var number = 3500.00;
if(Number.isInteger(number)){
var zeroappend= number.toLocaleString()+".00";
console.log(zeroappend);//3,500.00;
}else{
console.log(number.toLocaleString());
}

Related

JavaScript: parseFloat() strips trailing zeros

I have been trying to find a solution to the following problem. I have a string that is a floating-point number like,
var value = '12.30';
When I try to cast it to be a floating number
parseFloat('12.30'); // output is 12.3
I need a way for my logic to return 12.30, the actual value, and that too a number.
Solutions I checked used,
parseFloat('12.30').toFixed(2);
but this converts it to string type and that's not acceptable in my scenario.
Any help would be appreciated. Thanks!
It's not parseFloat()'s fault. Numerically speaking, 12.30 equals 12.3, even if you don't use parseFloat():
const x = 12.30;
console.log(x); // Prints "12.3"
You can just use unary plus from Type Conversions in JavaScript for get number value
var value = '12.30';
alert(parseFloat(value).toFixed(2)); // 12.30
alert(typeof +parseFloat(value).toFixed(2)); // number
Get new successess in development!

Display "$xx.90" instead of "$xx.9" in Javascript

When I use p=10000 ,r=15 and n=60 in the below ...
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100).toFixed(2));
x = 237.9 instead of 237.90.
If the combo of p, r and n result in a number that is not $xx.x", then the code snippet works fine ...ie. formats to 2 decimal places.
But why is it displaying 237.9 instead of 237.90?
When you call number.toFixed(2), you do indeed get a string representation of the number with two decimal digits:
var number = 237.9;
number.toFixed(2); // '237.90'
However, when you then use parseFloat on this, you convert it back to a number again; since a number does not contain information about the number of zeros to display, the last zero is dropped as it is printed:
parseFloat(number.toFixed(2)); // 237.9
To avoid this, simply don't convert your string back into a float, but use it as a string.
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100)).toFixed(2);
p=10000,r=15, n=60;
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100)).toFixed(2);
console.log(x)
Add toFixed after all operations. You need string, basically...

Converting Strings to Integer and get the persentage of two number

What I'm trying to do is to make a progress bar for donation. My html structure is:
<div class="hgoal" style="text-align: center;">My goal is to raise $<span id="mygoal">9,999.00</span></div>
<div class="donation-total">Total Donation<span id="total-donation">1,000.00</span></div>
my javascript so far is to get the innerHTML value of mygoal and total-donation.
var mygoal = document.getElementById("mygoal").innerHTML;
var totalgoal = document.getElementById("total-donation").innerHTML;
and I'm getting this as a result:
mygoal = "9,999.00";
total-donation = "1,000.00";
I believe this is a string and not an integer, and using parseInt() only give me the first digit number.
Can anyone give me an idea how can I make this into an integer that can use for computation? example:
mygoal + total-donation = 10,999.00
And also, any idea how can i get the percentage of this two varible?
Use .replace(/,/g,'') to replace commas, then you get the magic of type coercion to convert your string to a number during calculation...
var mygoal = document.getElementById("mygoal").innerHTML.replace(/,/g,'');
var totalgoal = document.getElementById("total-donation").innerHTML.replace(/,/g,'');
If you use + on strings, they will be appended to each other, but other mathematical operators (*/- etc...) will first coerce the strings into numbers. To force coercion, you can multiply by 1, or perhaps use Number("123123.123")...
Number(mygoal) + Number(totalgoal); // using addition, so coerce strings to numbers
(mygoal / total_donation) * 100; // does not need coercion
Your main issue is, that your numbers include colons. The parseFloat() call will work, once you replace these colons. You may use the following code to do so:
// define regexp to replace colons
var replaceColons = new RegExp(',', 'g');
// apply regex
num = num.replace(replaceColons, '');
mygoal=parseInt(mygoal.replace(/,/gi,"")) will give you mygoal=9999.
You should use parseFloat(), not parseInt() ...
More, you have to remove the commas from the string, since parseFloat() does not undertsand number formatting characters (like comma). So, for example:
mygoal = mygoal.replace(/,/g, '');
total_donation = total_donation.replace(/,/g, '');
To get the percentage of two numbers, use:
(mygoal / total_donation) * 100;
Note that in JavaScript you can't use 'minus' char (-) in variables names.
You could use for example 'underscore' char (_), or CamelCase, wich is the recommended style for variables in JavaScript.
You need to convert those Indian (maybe) numbers to valid Javascript numbers for the sum, then convert the output back to the initial format using Number.toLocaleString.
var mygoal = "9,999.00";
var total_donation = "1,000.00";
var total = Number((Number(mygoal.replace(/,/g, '')) + Number(total_donation.replace(/,/g, ''))).toFixed(2));
var finalResult = total.toLocaleString('en-IN',{minimumFractionDigits: 2 });
alert(finalResult);

Problems with JavaScript "parseInt()" decimal string

I get the total_amount in cart code of ecommerce web page, after I use toString function, but when I convert the 14.82 string to int number, the decimals disappear.
<script>
var total_amount_string = <?=json_encode($cart['total_pvp'])?>;//-> 14,82
var total_amount_int = parseInt(total_amount_string).toFixed(2); //-> 14.00(here is the error)
console.log(total_amount_string) //-> 14,82
console.log(total_amount_int) //-> 14.00
</script>
What's the matter?
If the input string is "14,82" and you want the value 14.82, you'll need to convert the , to a . and then use parseFloat:
var total_amount_int = parseFloat(
total_amount_string.replace(/,/g, ".")
).toFixed(2);
parseInt will only parse the leading part of the string that defines a whole number ("int" = "integer" = "whole number"), so it stops at the ,. parseFloat will parse a decimal number, but only understands . as the decimal point, not ,, even in locales where , is the decimal point.
you should use parseFloat() instead of parseInt(). Because integer number is not decimal.
An integer has no decimal part, so any number "casted" to int will lose its decimals. You should use parseFloat if you want to keep the decimal part.
On the other hand, make sure you are not using a comma: Javascript parse float is ignoring the decimals after my comma
Your number is using a "," separator. Unfortunately there is no locale settings for number parsing in JavaScript, so you are forced to a bit more hacky:
var total_amount_string = "14,823462";
var total_amount_float = parseFloat(total_amount_string.replace(",", ".")).toFixed(2);
document.getElementById("total_amount_string").innerText = total_amount_string;
document.getElementById("total_amount_float").innerText = total_amount_float;
total_amount_string: <span id="total_amount_string"></span>
<br />
total_amount_float: <span id="total_amount_float"></span>
The parseInt() function parses a string and returns an integer. ParseInt returns only the first number in the string is returned!. If the first character cannot be converted to a number, parseInt() returns NaN.

Plus operator problems in Jquery

I was trying with following script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#item1_number_1').keyup(function() {
var valone = $('#item1_number_1').val();
var valtwo = 5;
var total = ((valone) + (valtwo));
$('#item2_number_1').val(total.toFixed(2));
});
});
</script>
I do not get any result in the field. But when I assign multiple (*) instead of plus (+), I am getting result.
I cannot understand what the error is in "var total = ((valone) + (valtwo));"
You can only call toFixed on Numbers.
String * String will convert the strings to Numbers and multiply them giving you a Number.
String + String will concatenate the two Strings together giving you a String.
You need to convert the strings to Numbers manually before you try to add them together.
var total = (+valone) + (+valtwo);
Then Number + Number will add the two Numbers together giving you a Number.
The value of an input is always a string. "Adding" a string concatenates, giving another string. Strings do not have a toFixed method.
* however is unambiguously "multiply", giving a number and therefore a result.
var valone = parseFloat(document.getElementById('item1_number_1').value);
Use parseInt() to convert fetched value(valone ) to number, and calculate, something like this, please use this only when your number is not float(56.66),
var valone = parseInt($('#item1_number_1').val(), 10);
var valtwo = 5;
var total = ((valone) + (valtwo));
The fetched vaue is treated like string until you convert it into number.
UPDATE
After Archer pointed out, I came to know you are using toFixed() method, which supposed to expect float numbers. So in this case you should use parseFloat() as given below.
var valone = parseFloat($('#item1_number_1').val());
I think one of them is a string. Try parseInt(valone) to make it an int first.
The issue is the + operator can also be used to concat strings together. The * operator is ONLY for multiplication and therefore it implicitly converts your values to numbers.
So you either need to use parseInt, parseFloat, or Number to explicitly convert to a numeric type before using the + operator.

Categories

Resources