toFixed hanging my code - javascript

I am taking practice exercises and ran into this issue.
This problem asks:
“Prompt for a number greater than 1 and to 4 decimal places. Format
and write the number to the page displaying with only 2 digits past
the decimal point using the toFixed() method. (e.g. 12.35, not
12.3453)
Since this method is very new, it doesn't work in older browsers. See
if you can get only 2 digits past the decimal point to show without
using toFixed().”
I found the answer to the hard part through the archives here, Math.round(n*100)/100. Thanks for that. But when I tried the “easy” way, I get nothing. My work is at jsFiddle, but in a nutshell:
var num = prompt("Give me a number greater than one, with 4 decimal places.");
var num2 = prompt("Great! Do one more, please!");
num = Math.round(num*100)/100;
num2 = num2.toFixed(2);
alert(num);
alert(num2);
The exercise did not ask for a second number, but I wanted to use both methods in separate incidences. When I run this it does not alert anything. I know that it is hanging at the toFixed statement, because when I comment it out it alerts both as expected, num1 at 2 decimal places, and num2 as it was prompted (i.e. 1.2345).
So here is what I have done so far:
Mozilla’s developer page shows this format: n.toFixed(1);// Returns "12345.7": note rounding
Seems exactly what I am doing.
I copied and pasted all of it in my Sublime, making sure that I called the .js file just before the closing body tag, to make sure it wasn’t some loading problem I don’t understand.
Plus all sorts of little tweaking.
Sorry to keep asking these questions, but since I am self-study, I have where else to go!

You need to use parseFloat. Using the function will convert the string to a float type variable, allowing for the toFixed function to work properly.
num2 = parseFloat(num2).toFixed(2);

Related

Javascript toFixed() is not working as expected

I am using toFixed but the method does not operate as expected
parseFloat(19373.315).toFixed(2);
//19373.31 Chrome
Expected Output : 19373.32
parseFloat(9373.315).toFixed(2);
// 9373.32 Working fine
Why does the first example round down, whereas the second example round up?
The problem is that binary floating point representation of most decimal fractions is not exact. The internal representation of 19373.315 may actually be something like 19373.314999999, so toFixed rounds down, while 19373.315 might be 19373.315000001, which rounds up.
Why does the first example round down, whereas the second example round up?
Look at the binary representation of the two values in memory.
const farr = new Float64Array(2);
farr[0] = 19373.315;
farr[1] = 9373.315;
const uarr = new Uint32Array(farr.buffer);
console.log(farr[0], uarr[1].toString(2).padStart(32, 0) + uarr[0].toString(2).padStart(32, 0));
console.log(farr[1], uarr[3].toString(2).padStart(32, 0) + uarr[2].toString(2).padStart(32, 0));
Without diving into the details, we can see that the second value has an additional '1' at the end, which is lost in the first larger value when it is fit into 64 bits.
Other answers have explained why, I would suggest using a library like numeral.js which will round things as you would expect.
Assuming toFixed casts to 32-bit float;
Check with this utility...
19373.315 is stored as 19373.314453125 (an error of -0.000546875) in 32-bit floating point format.
This is despite (19373.315).toFixed(4) coming out as 19373.3150.
Even if this is "expected" or "intended", I'd still report it as a bug.
It should use a double during the rounding check, and thus proper rounding during conversion to fixed string.
I think the spec even says so. :\
In the V8 javascript engine source, the Number.prototype.toFixed function invokes DoubleToFixedCString in this file ...
There's probably some inappropriate optimization in there... (Looking into it.)
I'd suggest submitting an additional test case for V8 with 19373.315 specifically.
(19373.3150).toFixed(39) yields 19373.314999999998690327629446983337402343750.
Rounding occurs once to bring it up to 19373.315 - which is correct - but not at the right digit when rounding to 2 digits.
I think this should have a second pass on rounding here to catch edge cases like this. I think it might have to round to n+1 digits, then again to n digits. Maybe there's some other clever way to fix it though.
function toFixedFixed(a,n) {
return (a|0) + parseFloat((a % 1).toFixed(n+1)).toFixed(n).substr(1);
}
console.log(toFixedFixed(19373.315,2)); // "19373.32"
console.log(toFixedFixed(19373.315,3)); // "19373.315"
console.log(toFixedFixed(19373.315,4)); // "19373.3150"
console.log(toFixedFixed(19373.315,37)); // "19373.3149999999986903276294469833374023438"
console.log(toFixedFixed(19373.315,38)); // "19373.31499999999869032762944698333740234375"
console.log(toFixedFixed(19373.315,39)); // "19373.314999999998690327629446983337402343750"
(Adopted from my comments on Vahid Rahmani's answer, who is correct.)

Adding a whole number and a decimal in Javascript results in removal of the decimal?

I'm sure this is simple, but in my javascript code, I have two numbers. One contains a decimal, and the other doesn't, and I add them together (ie. 7.5 + 5), I am getting a result with NO decimal value.
Do I need to cast each number variable as a double? I know that all numbers are doubles in javascript - which is why I do not understand this behavior...
For instance, I have var answer = week1 + week2;. Does this make sense?
Thanks in advance!
I am sorry for wasting time - turns out I was using parseInt instead of parseFloat to gather the "week" values I spoke about.
Can someone please close this question or delete it? Before the shame consumes me?

JS what happens to my number [duplicate]

I've been trying to debug a problem today and I finally found out what the problem is. For some reason, when a number has a leading zero JavaScript does something really weird.
Example:
alert(132);
alert(0132);
var test = 0132;
alert(test);
JSFiddle: http://jsfiddle.net/U8sFu/3/
The first popup says "132," the second "90," and the third says "90."
My question is, why does the number 0132 become the number 90? This is really baffling to me!
A number with a leading 0 is parsed as an octal literal, which is in base 8.

Search string for numbers

I have a javascript chat bot where a person can type into an input box any question they like and hope to get an accurate answer. I can do this but I know I'm going about this all wrong because I don't know what position the number will appear in the sentence. If a person types in exactly:
what's the square root of 5 this works fine.
If he types in things like this it doesn't.
what is the square root of the 5
the square root of 5 is what
do you know what the square root of 5 is
etc
I need to be able to determine where the number appears in the sentence then do the calculation from there. Note the line below is part of a bigger working chatbot. In the line below I'm just trying to be able to answer any square root question regardless of where the number appears in the sentence. I also know there are many pitfalls with an open ended input box where a person can type anything such as spelling errors etc. This is just for entertainment not a serious scientific project. :)
if(
(word[0]=="what's") &&
(word[1]=="the") &&
(word[2]=="square") &&
(word[3]=="root") &&
(word [4]=="of") &&
(input.search(/\d{1,10}/)!=-1) &&
(num_of_words==6)
){
var root= word[5];
if(root<0){
document.result.result.value = "The square root of a negative number is not possible.";
}else{
word[5] = Math.sqrt(root);
word[5] = Math.round(word[5]*100)/100
document.result.result.value = "The square root of "+ root +" is "+ word[5] +".";
}
return true;
}
Just to be clear the bot is written using "If statemments" for a reason. If the input in this case doesn't include the words "what" and "square root" and "some number" the line doesn't trigger and is answered further down by the bot with a generic "I don't know type of response". So I'm hoping any answer will fit the format I am using. Be kind, I'm new here. I like making bots but I'm not much of a programmer. Thanks.
You can do this using a regular expression.
"What is the sqrt of 5?".match(/\d+/g);
["5"]
The output is an array containing all of the numbers found in the string. If you have more than one, like "Is the square root of 100 10?" then it will be
"Is the square root of 100 10?".match(/\d+/g);
["100", "10"]
so you can pick what number you want to use in your script.
You will need to use regular expressions, if you do not know what they are you should look them up as it would take too long to explain them in this response. Here is a useful website for regular expressions in JavaScript https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions.
Assuming that you know regular expressions you should first search for numbers and store all the numbers that you find, if no numbers are found print out an error message. As an added note, you may what to consider searching for mathematical constants such as pi or e. This should work
nums = someString./\d+|pi|e/gi
The next part is going to be hard but to boil it down to is core concept, you need to look for key words such as 'square root', 'times', or 'plus'. You should do this word by word going left to right. For example if a user inputs
What is 5 plus 3 minus 8?
you should detect the plus before the minus, while if this is inputted
What is 5 minus 3 plus 8?
You should detect the minus before the plus.
For operations that uses two numbers you need to take the first two numbers that you found and do the operation and replace the two numbers with the result. I am trying to use reverse polish notation if you do not quite understand what I am trying to do, look it up if do not know what it is.
I hope I understood your question correctly and provided some help to coming to a solution because what you asked is very hard but seems like fun. Good luck. Also as a warning I am not considering order of operations in my response.

Is there a way to truncate scientific notation numbers in Javascript?

As you all know since it is one of the most asked topic on SO, I am having problems with rounding errors (it isn't actually errors, I am well aware).
Instead of explaining my point, I'll give an example of what possible numbers I have and which input I want to be able to obtain:
Let's say
var a = 15 * 1e-9;
alert(a)
outputs
1.5000000000000002e-8
I want to be able to obtain 1.5e-8 instead, but I cannot just multiply by 10e8, round and divide by 10e8 because I don't know if it will be e-8 or e-45 or anything else.
So basically I want to be able to obtain the 1.5000002 part, apply toFixed(3) and put back the exponent part.
I could convert into a string and parse but it just doesn't seem right...
Any idea ?
(I apologize in advance if you feel this is one of many duplicates, but I could not find a similar question, only related ones)
Gael
You can use the toPrecision method:
var a = 15 * 1e-9;
a.toPrecision(2); // "1.5e-8"
If you're doing scientific work and need to round with significant figures in mind: Rounding to an arbitrary number of significant digits
var a = 15 * 1e-9;
console.log(Number.parseFloat(a).toExponential(2));
//the above formula will display the result in the console as: "1.50e-8"

Categories

Resources