How can I get a float of 0.00. The reason I need 0.00, is because I am going to be accumalating float values by adding. Hence starting with 0.00.
I tried
var tmp ='0.00'
tmp = parseFloat(tmp.toString()).toFixed(2);
totals = parseFloat(tmp)
tmp is 0.00 but totals is 0. How can I make total 0.00? I need it to stay as a float and not a string.
Thanks
You can use the string tmp variable and then when you need to add to it use:
tmp = (+tmp + 8).toFixed(2);
JSFIDDLE DEMO
Or simply write a function to do that seeing that you'll have to do that many times:
function strAdd( tmp, num ) {
return (+tmp + num).toFixed(2);
}
There is no such thing as an integer type in javascript. There is only Number, which is stored as a double precision floating point. So to get a floating point value with 0.00, you need only to do this:
var tmp = 0;
var tmp ='0.00'
tmp = parseFloat(tmp.toString()).toFixed(2);
totals=parseFloat(tmp).toFixed(2);
alert(totals); //0.00
parseFloat() without toFixed() removes zeros after dot. So you need to add toFixed() again.
Here is dynamic floatParser for those who need
function customParseFloat(number){
if(isNaN(parseFloat(number)) === false){
let toFixedLength = 0;
let str = String(number);
// You may add/remove seperator according to your needs
[".", ","].forEach(seperator=>{
let arr = str.split(seperator);
if( arr.length === 2 ){
toFixedLength = arr[1].length;
}
})
return parseFloat(str).toFixed(toFixedLength);
}
return number; // Not a number, so you may throw exception or return number itself
}
You can use parseFloat function in Javascript.
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var a = parseFloat("10") + "<br>";
var b = parseFloat("10.00") + "<br>";
var c = parseFloat("10.33") + "<br>";
var d = parseFloat("34 45 66") + "<br>";
var e = parseFloat(" 60 ") + "<br>";
var f = parseFloat("40 years") + "<br>";
var g = parseFloat("He was 40") + "<br>";
var n = a + b + c + d + e + f + g;
document.getElementById("demo").innerHTML = n;
}
</script>
Related
So I'm trying to learn javascript, and I want to find the median of some numbers that I insert into a prompt when I click on the button "find median".
function Media()
{
var n = prompt("number of elements?");
var i = 1;
var s = 0;
for (i=1;i<=n;i++)
{
var m = prompt("insert # " +i);
s = s+m;
}
var media = s/n;
document.getElementById("rezultat").innerHTML = "result: " +media
}
I made a test with two numbers, 1 and 2, and the median was 6, and i cant figure what i've done wrong
You should parse the result of prompt to an integer;
How to convert a string to an integer in JavaScript?
function Media() {
var n = parseInt(prompt("number of elements?"));
var i = 1;
var s = 0;
for (i=1;i<=n;i++)
{
var m = prompt("insert # " +i);
m = parseInt(m);
s = s+m;
}
var media = s/n;
document.getElementById("rezultat").innerHTML = "result: " +media
}
Media();
<div id='rezultat' />
You should also parse the result of prompt using parseInt
var m = parseInt(prompt("insert # " + i));
s/n gives the mean of the input. If you are looking for the median, you should use an array to store the inputs and get the element(s) in the middle.
I want an eval() function which will calculate brackets as same as normal calculations but here is my code
var str = "2(3)+2(5)+7(2)+2"
var w = 0;
var output = str.split("").map(function(v, i) {
var x = ""
var m = v.indexOf("(")
if (m == 0) {
x += str[i - 1] * str[i + 1]
}
return x;
}).join("")
console.log(eval(output))
Which takes the string str as input but outputs 61014 and whenever I try evaluating the output string, it remains same.
Obligatory "eval() is evil"
In this case, you can probably parse the input. Something like...
var str = "2(3)+2(5)+7(2)+2";
var out = str.replace(/(\d+)\((\d+)\)/g,(_,a,b)=>+a*b);
console.log(out);
while( out.indexOf("+") > -1) {
out = out.replace(/(\d+)\+(\d+)/g,(_,a,b)=>+a+(+b));
}
console.log(out);
You can do it much simplier, just insert '*' in a right positions before brackets
var str = "2(3)+2(5)+7(2)+2"
var output = str.replace(/\d\(/g, v => v[0] + '*' + v[1])
console.log(eval(output))
In my code I have a variable myCash, which is printed into an h1 element using javaScript's innerHTML. I found a function online that puts a comma after every third character from the end of the number so that the number is easier to read. I've tried for a couple of hours now sending my variable myCash into the function and then print it on the screen. I CANNOT get it to work.
I've tried just alerting the new variable to the screen after page load or by pressing a button, but I get nothing and the alert doesn't even work. Here's the comma insert function:
function commaFormatted(amount) {
var delimiter = ","; // replace comma if desired
amount = new String(amount);
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
now when I want my variable to change I've tried it a few different ways including this:
var newMyCash = commaFormatted(myCash);
alert(newMyCash);
and this:
alert(commaFormatted(myCash);
Where of course myCash equal some large number;
This does absolutely nothing! What am I doing wrong here??
Also,
Try this as a drop in replacement and try alerting the response:
http://phpjs.org/functions/number_format:481
Do you see any errors in the console of your browser (usually f12)?
This is not my function, but I hope it helps you.
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Usage:
var newMyCash = addCommas( myCash ); alert( newMyCash );
Source: http://www.mredkj.com/javascript/nfbasic.html
You are most likely not passing in a number that contains a decimal, which the function expects.
Working Demo
I've never done this before and am not sure why it's outputting the infamous � encoding character. Any ideas on how to output characters as they should (ASCII+Unicode)? I think \u0041-\u005A should print A-Z in UTF-8, which Firefox is reporting is the page encoding.
var c = new Array("F","E","D","C","B","A",9,8,7,6,5,4,3,2,1,0);
var n = 0;
var d = "";
var o = "";
for (var i=16;i--;){
for (var j=16;j--;){
for (var k=16;k--;){
for (var l=16;l--;){
d = c[i].toString()
+ c[j].toString()
+ c[k].toString()
+ c[l].toString();
o += ( ++n + ": "
+ d + " = "
+ String.fromCharCode("\\u" + d)
+ "\n<br />" );
if(n>=500){i=j=k=l=0;} // stop early
}
}
}
}
document.write(o);
The .fromCharCode() function takes a number, not a string. You can't put together a string like that and expect the parser to do what you think it'll do; that's just not the way the language works.
You could ammend your code to make a string (without the '\u') from your hex number, and call
var n = parseInt(hexString, 16);
to get the value. Then you could call .fromCharCode() with that value.
A useful snippet for replacing all unicode-encoded special characters in a text is:
var rawText = unicodeEncodedText.replace(
/\\u([0-9a-f]{4})/g,
function (whole, group1) {
return String.fromCharCode(parseInt(group1, 16));
}
);
Using replace, fromCharCode and parseInt
If you want to use the \unnnn syntax to create characters, you have to do that in a literal string in the code. If you want to do it dynamically, you have to do it in a literal string that is evaluated at runtime:
var hex = "0123456789ABCDEF";
var s = "";
for (var i = 65; i <= 90; i++) {
var hi = i >> 4;
var lo = i % 16;
var code = "'\\u00" + hex[hi] + hex[lo] + "'";
var char = eval(code);
s += char;
}
document.write(s);
Of course, just using String.fromCharCode(i) would be a lot easier...
I have a number in JavaScript that I'd like to convert to a money format:
556633 -> £5566.33
How do I do this in JavaScript?
Try this:
var num = 10;
var result = num.toFixed(2); // result will equal string "10.00"
This works:
var currencyString = "£" + (amount/100).toFixed(2);
Try
"£"+556633/100
This script making only integer to decimal.
Seperate the thousands
onclick='alert(MakeDecimal(123456789));'
function MakeDecimal(Number) {
Number = Number + "" // Convert Number to string if not
Number = Number.split('').reverse().join(''); //Reverse string
var Result = "";
for (i = 0; i <= Number.length; i += 3) {
Result = Result + Number.substring(i, i + 3) + ".";
}
Result = Result.split('').reverse().join(''); //Reverse again
if (!isFinite(Result.substring(0, 1))) Result = Result.substring(1, Result.length); // Remove first dot, if have.
if (!isFinite(Result.substring(0, 1))) Result = Result.substring(1, Result.length); // Remove first dot, if have.
return Result;
}
Using template literals you can achieve this:
const num = 556633;
const formattedNum = `${num/100}.00`;
console.log(formattedNum);