[SOLVED] Question 19: Unable to make float with 2 decimals


#1

I attempted to do 19, but I was only ever getting [ 9,7 ], or [ ‘9.00’, ‘7.00’ ]. I can’t seem to force JS to keep a float as 2 decimal places, it just truncates to the lowest decimal place it needs.

toFixed(2) will return a string that has 2 decimal places, but the moment I convert it back to a float the 0s disappears…

Any ideas on how to do this?

SOLVED: My issue was that the guides all say to use Math.round() in addition to toFixed(2)… I removed the rounding and it not accepts it even if it is an array of strings…


#2

Convert to a float for the calculations, which I’m assuming you are doing by what you wrote there. And only use toFixed in the return statement for displaying it.


#3

I tried using this parseFloat(Math.round(num * 100) / 100).toFixed(2); but I will return a string [ ‘9.00’, ‘7.00’ ] how do I make this string dispay to [9.00, 7.00] in JS.


#4

I see what you are saying, but I believe javascript will drop the trailing decimal places if they are zero. I returned as strings and it was accepted, since they state “make sure your results always return 2 decimal places”. Which I took as return 2 decimal places even if they are zero’s therefore has to be a string in javascript. If anyone finds a different way, let us know.


#5

Interesting. I returned the results as numbers with 2 decimal places and it also accepted it. I guess they’re not doing === to check the values.


#6

toFixed() always return a string so if you want for the results to be a number, you would have to convert each element back to number after calling toFixed() on the element.


#7

@kpalos the issue with converting it back to a number is that it cuts off any trailing 0s. So my array is actually just [ 9, 7 ]


#8

What did you use to convert it back to number? I just wrapped the whole thing in Number() and it worked for me.


#9

@RexChiu I just ran it in node and you are right, it removes trailing zeroes still. Which is really weird since it accepted my code.


#10

I think what is also being put through the test is different sized Grids. Make sure you arent hardcoding a grid size value (dividing by a hard 100) and setting it up so it’ll work with any grid size, and not just the default 10x10 lighthouse one.

My code would not pass (even tho I was still getting 9 and 7) until i caught on to this.


#11

Make sure you arent hardcoding a grid size value (dividing by a hard 100) and setting it up so it’ll work with any grid size

Man, if only we had a handy function that just automatically returned the grid size (coughchallenge#4)


#12

you might want to check on that cough. Sounds nasty