3

I am trying to convert numbers in following formats

0 -> 0.00
1 -> 1.00
1.1 -> 1.10
4.0  -> 4.00

But problem is its returning as string only

value = 0;
var s = Math.floor(value / 60) + "." + (value % 60 ? value % 60 : '00');
console.log(s+s); //just checking if its number

But its returning as string , I tried parseInt , but its returning only 0 . I tried ParseFloat and fixedTo(2) , its returning as string only.

Vishnu
  • 2,372
  • 6
  • 36
  • 58
  • 1
    If you format a number for display it becomes a string. There's no other way. – Álvaro González May 25 '17 at 07:20
  • @Rajesh : it returns string – Vishnu May 25 '17 at 07:22
  • `0` and `0.00` are _literals_ representing the same number value. You cannot get a Number _literal_ by definition; only a string. It's not clear, though, what exactly you're trying to do here. – raina77ow May 25 '17 at 07:24
  • You can convert the string into number using the `Number` function i.e. Number('1.10') return 1.1 as number, but you cannot maintain the format you want. – Max May 25 '17 at 07:25
  • why do you need this kind of *"numbers"*? – Nina Scholz May 25 '17 at 07:26
  • Take a look to this [question](https://stackoverflow.com/questions/2283566/how-can-i-round-a-number-in-javascript-tofixed-returns-a-string), maybe it will help you – Carlos Mayo May 25 '17 at 07:28
  • I want to pass this number to a function to make my slider work , that function is not accepting this strings – Vishnu May 25 '17 at 07:29
  • I am using nouiSlider – Vishnu May 25 '17 at 07:29
  • it looks, that *nouiSlider* is working with numbers. for display, like [this](https://refreshless.com/nouislider/examples/#section-non-linear), it uses `toFixed` method. – Nina Scholz May 25 '17 at 07:33

1 Answers1

11

As seen in the comments, there is no way for that in JavaScript. Formatting a Number always returns a Srting. For this you have some possibilities, though

Number(1).toFixed(2) // "1.00" - setting the number of digits after the decimal point
Number(1).toPrecision(2) // "1.0" - setting the number of digits

These are for printing it out, so normally, it shouldn't matter if it is a String or a Number.

Then if you want to use it as a Number, you just follow @Max 's advice and convert it using the function Number(str) or the shorthand +str.

Misu
  • 441
  • 5
  • 15
  • Its not for printing , Its for passing to another function – Vishnu May 25 '17 at 07:41
  • What is that other function has to do with formatted numbers, may I ask? In my mind if a function needs a Number it is all the same if it gets it formatted or not. But perhaps I lack a bit of imagination... – Misu May 25 '17 at 07:50