I've figured out in the past that if I want a number 100000 to have commas then I just add .toLocaleString() to the angularJS variable. ie:
<span>{{variable.toLocaleString()}}</span>
Also, if want to limit the number of decimal places to a number 20.34343434 to lets say 2, then I would just add .toFixed(2). ie:
<span>{{variable.toFixed(2)}}</span>
Now I would like to do both. ie:
<span>{{variable.toFixed(2).toLocaleString()}}</span>
or
<span>{{variable.toLocaleString().toFixed(2)}}</span>
but neither seem to work. Maybe the solution to this has nothing to do with either function.
Question: How do I add commas and limit the amount of decimal places in a value using HTML and angularJS?
You can do this with a currency filter using an empty string for the currency symbol:
{{variable | currency:""}}
If you want to change the number of decimal places, you can specify it as an argument (default is 2):
{{variable | currency:"":3}}
If you insist on using function then you can use:
{{variable.toLocaleString("nu", {minimumFractionDigits: 2, maximumFractionDigits: 2})}}
This will take care of both commas/spaces (depending on locale) in integer digits as well as separator (. or ,) depending on locale.
Related
In JS, I do have a float number which come from php as below:
var number = 2,206.00
In JS, I need to use parseFloat that number.
So I tried parseFloat(number), but its give only 2. So how can I get 2206.00 instead of 2?
Number.parseFloat is the same function object as globalThis.parseFloat.
If globalThis.parseFloat encounters a character other than:
a plus sign or,
a minus sign or,
a decimal point or,
an exponent (E or e)
...it returns the value up to that character, ignoring the invalid character and characters following it. A second decimal point also stops parsing.
So the following prints 2. And this seems to be your problem.
console.log(parseFloat('2,206.00')) // 2
Solution: use string manipulation to remove any commas from the number (really a String before parsing it.
console.log(parseFloat('2,206.00'.replaceAll(',', ''))) // 2206
If you need to store the value as a number but render it as a formatted string, you may need Number#toFixed to render the values after the decimal point:
console.log((2206).toFixed(2)) // '2206.00'
Final note: be careful about localization because some countries use commas for decimal points and decimal points for number grouping. As #t.niese says: store number values without localization, and then apply localization at the surface of your app. But that is a wider, more complicated topic.
You have to remove comma first and use parseFloat.
And about 2 decimal after dot, I see you use number_format($myNumber, 2) in PHP, so in JS, you use .toFixed(2).
var number = '2,206.00';
var result = parseFloat(number.replace(/,/g, '')).toFixed(2);
console.log(result);
First of all what you currently have most probably would trigger an Unexpected number error in JS.
It seems the generated value comes from the number_format() PHP function which returns a string. Moreover the var number variable should also be considered a string as we have a string format.
So firstly you should quote var number = '2,206.00' after that, you have to make the string float-like in order to parse it as float so we should replace , with empty string in order for the number to become 2206.00 number = number.replace(",",""). Lastly the parse should be done now in order to convert the float-like string to an actual float parseFloat(number).
Whole code:
var number = '2,206.00';
number.replace(",","");
number = parseFloat(number);
ok, basically you want a two decimal number after point like (20.03),
try this
parseFloat(number).toFixed(2)
I have a script for taking data entered into a Price field on my editor and splitting it across a Pounds and Pence field based on the . symbol.
Now I've been asked if I could multiply the Price field by 1.2 and display the result in the Pounds field. The pence field would no longer be needed.
I have no idea if multiplication can even work and especially using decimal points... Can anyone explain how I should rewrite the below?
$('#price1').keyup(function(event) {
if ($('#price1').val().indexOf('.') != -1){
$('#pence1').val($('#price1').val().substr($('#price1').val().indexOf('.') + 1, $('#price1').val().lengh));
$('#pound1').val($('#price1').val().substr(0, $('#price1').val().indexOf('.')));
}else{
$('#pound1').val($('#price1').val());
};
});
Some things to remark:
Your current solution has a spelling mistake for length.
Don't locate the decimal point. Instead use native JavaScript capabilities to evaluate the input. You can use parseFloat(), Number() or the unary plus operator for that.
Once you have the numeric value, you can multiply using the * operator. As multiplication will also convert its operands to number, you don't even need the previous advice, although it is still good practice to first do the conversion to number and then do the arithmetic.
Use the input event instead of the keyup event: input is not always the result of key events (think copy/paste via context menu, drag/drop, other devices...)
Here is the proposed solution:
$('#price1').on("input", function(event) {
var num = +$('#price1').val(); // convert to number using unary plus operator
// multiply, format as string with 2 decimals, and convert back to number
num = +(num * 1.2).toFixed(2)
$('#pound1').val(num); // output
});
var randomNumber = (Math.random()*3 + 3.5); randomNumber;
alert(randomNumber)
This piece of code returns a number like
4.589729345235789
I need it to return
4.5
So need it to remove all the numbers after the decimal except the first one, can anyone show me how to do that?
You use Number.prototype.toPrecision() with parameter 2, Number.prototype.toFixed() with parameter 1.
+randomNumber.toPrecision(2);
Alternatively, you can use String.prototype.slice() with parameters 0, 3
+String(randomNumber).slice(0, 3);
If you need to set the amount of decimal places in a number, you can use toFixed(X), where X is the amount of decimal places you want to have.
For example,
4.589729345235789.toFixed(1); would result in 4.6.
Keep in mind, this will convert the number into a string.
If you need absolute accuracy and 4.6 is not good enough for you, see this Stackoverflow post, which has this as a more "accurate" method for your case:
var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
Notice the {0,2} inside of that, which is the range. You can change it to {0,1} in your case.
How to keep '.00' in Javascript? I currently have the string "123456789012.00";
I want to get the double 123456789012.00 to keep .00
toFixed(2) will return a string
parseFloat() will cast the .00
How can I do this?
A float uses the precision it needs (that's why it's called a "float" -- as in "floating point", the point has no fixed position).
If you want to display a float with the 2 significant digits (i.e. 2 digits after the point), you can use toFixed(2). That will not change the number, but will store it in a string with the number of digits you want to show.
You can use the toFixed() method to do this. The code below will log the result you want in the console of your browser.
var num = "123456789012.00";
console.log(parseFloat(num).toFixed(2));
I need regex to validate a number that could contain thousand separators or decimals using javascript.
Max value being 9,999,999.99
Min value 0.01
Other valid values:
11,111
11.1
1,111.11
INVALID values:
1111
1111,11
,111
111,
I've searched all over with no joy.
/^\d{1,3}(,\d{3})*(\.\d+)?$/
About the minimum and maximum values... Well, I wouldn't do it with a regex, but you can add lookaheads at the beginning:
/^(?!0+\.00)(?=.{1,9}(\.|$))\d{1,3}(,\d{3})*(\.\d+)?$/
Note: this allows 0,999.00, so you may want to change it to:
/^(?!0+\.00)(?=.{1,9}(\.|$))(?!0(?!\.))\d{1,3}(,\d{3})*(\.\d+)?$/
which would not allow a leading 0.
Edit:
Tests: http://jsfiddle.net/pKsYq/2/
((\d){1,3})+([,][\d]{3})*([.](\d)*)?
It worked on a few, but I'm still learning regex as well.
The logic should be 1-3 digits 0-1 times, 1 comma followed by 3 digits any number of times, and a single . followed by any number of digits 0-1 times
First, I want to point out that if you own the form the data is coming from, the best way to restrict the input is to use the proper form elements (aka, number field)
<input type="number" name="size" min="0.01" max="9,999,999.99" step="0.01">
Whether "," can be entered will be based on the browser, but the browser will always give you the value as an actual number. (Remember that all form data must be validated/sanitized server side as well. Never trust the client)
Second, I'd like to expand on the other answers to a more robust (platform independent)/modifiable regex.
You should surround the regex with ^ and $ to make sure you are matching against the whole number, not just a subset of it. ex ^<my_regex>$
The right side of the decimal is optional, so we can put it in an optional group (<regex>)?
Matching a literal period and than any chain of numbers is simply \.\d+
If you want to insist the last number after the decimal isn't a 0, you can use [1-9] for "a non-zero number" so \.\d+[1-9]
For the left side of the decimal, the leading number will be non-zero, or the number is zero. So ([1-9]<rest-of-number-regex>|0)
The first group of numbers will be 1-3 digits so [1-9]\d{0,2}
After that, we have to add digits in 3s so (,\d{3})*
Remember ? means optional, so to make the , optional is just (,?\d{3})*
Putting it all together
^([1-9]\d{0,2}(,?\d{3})*|0)(\.\d+[1-9])?$
Tezra's formula fails for '1.' or '1.0'. For my purposes, I allow leading and trailing zeros, as well as a leading + or - sign, like so:
^[-+]?((\d{1,3}(,\d{3})*)|(\d*))(\.|\.\d*)?$
In a recent project we needed to alter this version in order to meet international requirements.
This is what we used: ^-?(\d{1,3}(?<tt>\.|\,| ))((\d{3}\k<tt>)*(\d{3}(?!\k<tt>)[\.|\,]))?\d*$
Creating a named group (?<tt>\.|\,| ) allowed us to use the negative look ahead (?!\k<tt>)[\.|\,]) later to ensure the thousands separator and the decimal point are in fact different.
I have used below regrex for following retrictions -
^(?!0|\.00)[0-9]+(,\d{3})*(.[0-9]{0,2})$
Not allow 0 and .00.
','(thousand seperator) after 3 digits.
'.' (decimal upto 2 decimal places).