0

I tried to convert number to string in JavaScripts using toString() but it truncates insignificant zeros from numbers. For examples;

var n1 = 250.00 
var n2 = 599.0 
var n3 = 056.0 

n1.toString() // yields  250
n2.toString() // yields 599
n3.toString() // yields 56

but I dont want to truncate these insignificant zeros ( "250.00"). Could you please provide any suggestions?. Thank you for help.

Aarav
  • 111
  • 1
  • 10

2 Answers2

3

The number doesn't know how many trailing 0 there are because they are not stored. In math, 250, 250.00 or 250.0000000000000 are all the same number and are all represented the same way in memory.

So in short, there is no way to do what you want. What you can do is format all numbers in a specific way. See Formatting a number with exactly two decimals in JavaScript.

Community
  • 1
  • 1
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
0

As far as I know, you can't store number with floating zeros, but you can create zeroes with floating zeroes, by using toFixed:

var n1 = 250;
var floatedN1 = n1.toFixed(2); //type 'string' value '250.00'
Ziki
  • 1,256
  • 1
  • 15
  • 31
  • 10X, I fixed my mistake – Ziki Nov 04 '15 at 16:06
  • If I understand correct he don't need fixed decimals, he need to leave them as is. So `599.0` should be remain `599.0`, not `599.00`. – hindmost Nov 04 '15 at 16:06
  • So where he get the number he should store it as string, or keep somewhere how many zeroes he want at each point, and he can change the argument in the function to any number he want. for 599.0 he should use `toFixed(1)` – Ziki Nov 04 '15 at 16:07
  • In my case , 250, 250.0 and 250.00 have different meanings – Aarav Nov 04 '15 at 16:08
  • 3
    @Aarav: Then you have to store string values in the first place. – Felix Kling Nov 04 '15 at 16:09