0

When I round of the number 1.4034 to two decimals I get 1.4 instead of 1.40. How do I get 1.40? I can use toFixed(2) but that returns a string. I need it to be a float. Any ideas?

Here's my code

var num = 1.40345;
var stringnumber = Math.round(num * 100) / 100;

Update: The reason I want to this is because I'm using the chart library highchart which only excepts float values. The float value is printed on each bar and it looks odd when some values are with one decimal and some with two.

Joe
  • 4,274
  • 32
  • 95
  • 175

3 Answers3

0

This is silly. 1.40 === 1.4... Why could you possibly want 1.40 as a float?

Basically, it's impossible.

For example, try this.

parseFloat('1.40')

You'll just end up with 1.4 again.

Nate Higgins
  • 2,104
  • 16
  • 21
0

When stringnumber is a number, it makes no difference for 1.4 and 1.40, because 1.4.toFixed(2) is "1.40".

The precision only matters when you print it out, i.e. as a string.

yzn-pku
  • 1,082
  • 7
  • 14
0

1.4 vs 1.40 only has merits when you are talking about a visual representation like printing a string.

When talking about the datatype Number you cannot distinguish between 1.4 and 1.40 since that is exactly the same thing.

Jacob T. Nielsen
  • 2,938
  • 6
  • 26
  • 30