This question already has answers here:
Formatting a number with exactly two decimals in JavaScript
(32 answers)
Closed 7 years ago.
Here's the code
<script type="text/javascript">
$(document).ready(function(){
$('input.number')
.on("blur", function(e){
var $this = $(this);
var num = $this.val().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
$this.val(num);
});
});
</script>
The output of that code is 10000 => 10,000
I want the output to be 10000 => 10,000.00
thanks..
You could also make use of toLocaleString with minimumFractionDigits property of its options argument.
numObj.toLocaleString([locales [, options]])
Example:
var number = 10000;
alert(number.toLocaleString('en-US', { minimumFractionDigits: 2 }));
Note: Supported by all modern browsers, except Safari (it seems)
Use this:
parseFloat(num).toFixed(2)
Like:
$this.val(parseFloat(num).toFixed(2));//output 1000.00
For comma separator use this SO ANSWER.
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}
var num = 10000;
console.log(commaSeparateNumber(parseFloat(num).toFixed(2)));// output 10,000.00
DEMO
Related
This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 2 years ago.
I want to format a number (225121894) so its formatted as 225,121,894 I pull all the numbers from a JSON and sort and process.
Here is my code
function getTestStats(jsonData)
{
let totalTest = 0
let totalCases = 0
jsonData.map(covid =>
{
if(covid.tested !== "NA") totalTest += Number(covid.tested)
})
document.getElementById('covidTestStatPG').innerHTML += `${totalTest}`
}
Try using Number.toLocaleString(). Not only does this handle the problem of comma-separation, but it handles any type of locale-standard display settings. Below, I use en-US, but not every country/region formats commas the same, so this allows you to change as needed (i.e., to en-IN for Indian-English, etc.) without coding it up yourself everytime...
var number = 123456789;
console.log(number.toLocaleString('en-US'));
/*
CODE FOR NUMBER FORMAT
*/
function numFormat(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
console.log( numFormat(224405) );
/*
YOUR CODE
*/
var jsonData = [{tested:"225121894"}]; // Dummay JSON Data
function getTestStats(jsonData)
{
let totalTest = 0
let totalCases = 0
jsonData.map(covid =>
{
if(covid.tested !== "NA") totalTest += Number(covid.tested)
})
document.getElementById('covidTestStatPG').innerHTML += `${numFormat(totalTest)}`
}
getTestStats(jsonData)
<div id="covidTestStatPG">🎁</div>
You may want to check out Intl.NumberFormat.
I've used it before as follows (this is typescript but you get the idea):
const locale = "en-US";
static formatNumber(rawNumber?: number) {
return rawNumber ? Intl.NumberFormat(locale).format(rawNumber) : "-";
}
This question already has answers here:
javascript - how to prevent toFixed from rounding off decimal numbers
(7 answers)
Closed 5 years ago.
I am defining my numberfield and then I amgetting some value like this
val = 3.555678
I am using decimalPrecision : 3 in my number field so The value is displaying is 3.556
I want my value should be display 3.555 so for that I am using
val = val.toFixed(3);
val is coming in consol 3.555
then numberfield.setValue(val);
But in UI it is still comming 3.556
Why it is coming this.
I you want to display 3.555 you can do it in the following way
let val = 3.555678
let decimalPrecision = 3;
let roundedval = val.toFixed(3);
if(roundedval > val){
val = roundedval - Math.pow(10, -1*decimalPrecision);
}
console.log(val);
You can use:
var val=3.555678;
val = Math.floor (val*1000)/1000;
console.log(val);
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 6 years ago.
I'm not sure what's wrong.
There are two variables, cena and uhrada. cena = 10 and uhrada = 279.8. I want to add them but I am getting 279.810 instead of 289.8.
Thanks for any help!
function priplatok(vstup1, vstup2) {
var chid = vstup1;
var cena = vstup2;
var uhrada = document.getElementById('uhr').value;
if (document.getElementById(chid).checked) {
var pridatu = uhrada + cena;
alert(pridatu);
}
}
The reason is that the values you take from the HTML input elements are always strings, even when they look like numbers. You have to first convert them, for instance with parseInt(...) or parseFloat():
var pridatu = parseFloat(uhrada) + parseFloat(cena);
A shorter way is to force conversion with a +:
var pridatu = +uhrada + +cena;
Although this is concise, you should probably first check if the input really is numeric. I refer to a popular question "Validate decimal numbers in JavaScript - IsNumeric()".
You get a string from document.getElementById('uhr').value.
If you want to do math, you need to cast the value either with parseInt(string, 10) or with parseFloat(string) to a number, implicit with a unary plus.
Your code:
function priplatok(vstup1, vstup2) {
var chid = vstup1;
var cena = vstup2;
var uhrada = +document.getElementById('uhr').value; // use implicit cast to number
if (document.getElementById(chid).checked) {
var pridatu = uhrada + cena;
alert(pridatu);
}
}
Thats because the values are strings and not numbers.
You have to make them numbers first and then calculate:
var pridatu = parseInt(uhrada) + parseInt(cena);
This question already has an answer here:
Simple Javascript Math Function- addition/not working?
(1 answer)
Closed 7 years ago.
I have a some problem on my jquery code.
I want counting 1 + 1 in jquery but the result is "11" not "2" ... so where the problem ??
Here is my code :
$(document).ready(function () {
var hasil = $(".hitdethasil>.hasildet");
var bhit = $(".hitung");
$(bhit).click(function(){
var ske = $(".iUn").val(); //assume is 1
var ska = $(".ia").val(); //assume is 1
var beda = $(".ib").val(); //assume is 1
var hasilarit = ska + (ske - 1) * beda; //but in this result is 10 should the result is 1.
$(hasil).text(hasilarit);
console.log(hasilarit);
});
$(".iUn").keyup(function () {
var thisis = $(this).val();
$(".skun").text(thisis);
});
});
Where does the fault ????
Thanks B4 and i'm sorry for my bad english ... :)
Here is JsFiddle to see the problem ... http://jsfiddle.net/bagusa4/mqLqoL7o/
This var ske = $(".iUn").val(); is "1" not 1. The same holds for the other textbox. So "1"+"1"="11", which is the expected.
Otherwise, you should use the parseInt -assuming that the input will be an integer. Otherwise you should use the parseFloat function-.
var ske = parseInt($(".iUn").val());
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Generating random numbers in Javascript
Hi..
I want to generate random numbers (integers) in javascript within a specified range. ie. 101-999. How can I do that. Does Math.random() function supports range parameters ?
Just scale the result:
function randomInRange(from, to) {
var r = Math.random();
return Math.floor(r * (to - from) + from);
}
The function below takes a min and max value (your range).
function randomXToY(minVal,maxVal)
{
var randVal = minVal+(Math.random()*(maxVal-minVal));
return Math.round(randVal);
}
Use:
var random = randomXToY(101, 999);
Hope this helps.
Math.floor(Math.random()*898)+101