0

I have a problem concatenating a json.

I'm doing:

jsonb = jsonb.concat(1.200);

Then When I use the jsonb I see "1.2" but not "1.200" I need the number with zeros, how can I do it?

pmiranda
  • 7,602
  • 14
  • 72
  • 155
  • zeros at the end of a number are ingored, make it string – Marios Nikolaou Jan 11 '19 at 16:46
  • 1
    there is no such thing as "a number with zeros" as javascript floating points don't have precision. 1.2 and 1.200 are the same number... if this is a display field you can format the number however you want later – Leroy Stav Jan 11 '19 at 16:46
  • @LeroyStav, would you please elaborate on "javascript floating points don't have precision"? – Vitaliy Terziev Jan 11 '19 at 16:59
  • http://mathworld.wolfram.com/Precision.html – Leroy Stav Jan 11 '19 at 17:02
  • @LeroyStav, what the quoted link has to do with JavaScript specifically, compared to what? – Vitaliy Terziev Jan 11 '19 at 17:03
  • Oh... compared to, say, c++ http://www.cplusplus.com/reference/iomanip/setprecision/ ... afaik plenty of languages have ways of setting precision and having that precision be reflected on cast, but partially because of javascript's loose-typedness this just doesn't exist – Leroy Stav Jan 11 '19 at 17:27

2 Answers2

1

1.200 is not a number that most systems want to work with, so they would truncate it to 1.2. As others have stated, you could use the toFixed method to fix this, or simply make this value a string. Since you don't need the zeros for math, it's clear you want them to be visual, so you could just make it a string.

jsonb = jsonb.concat('1.200');
bronkula
  • 633
  • 5
  • 12
0

You can use toFixed on a number value, but as others have pointed out, numbers by themselves have no trailing zeroes, this function returns a string.

console.log(1.200); // 1.2, no trailing zeroes
console.log(1.2.toFixed(3)); // 1.200, trailing zeroes

let someValue = 1.25;
console.log(someValue.toFixed(0)); // 1
console.log(someValue.toFixed(1)); // 1.3
console.log(someValue.toFixed(2)); // 1.25
console.log(someValue.toFixed(3)); // 1.250

let val = someValue.toFixed(2);
console.log(typeof someValue); // number
console.log(typeof val); // string
Drew Reese
  • 165,259
  • 14
  • 153
  • 181