Aarav
Aarav

Reputation: 111

Converting number into string in JavaScripts without trailing zeros from number

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.

Upvotes: 0

Views: 194

Answers (2)

Felix Kling
Felix Kling

Reputation: 816322

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.

Upvotes: 3

Ziki
Ziki

Reputation: 1440

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'

Upvotes: 0

Related Questions