Tuesday, December 14, 2021

Convert Number, String, Float and Format JSON

 1) Convert to String

To quickly convert a number to a string, we can use the concatenation operator (+) plus followed by an empty set of quotation marks "" .

let val = 1 + "";
console.log(val); // Result: "1"
console.log(typeof val); // Result: "string"

2) Convert to Number

The opposite can be quickly achieved using the addition operator + .

let int = "15";
int = +int;
console.log(int); // Result: 15
console.log(typeof int); Result: "number"

This may also be used to convert Booleans to numbers, as below:

console.log(+true);  // Return: 1
console.log(+false); // Return: 0

3)Quick Float to Integer

If you want to convert a float to an integer, you can use Math.floor() , Math.ceil() or Math.round() . But there is also a faster way to truncate a float to an integer using |, the bitwise OR operator.

console.log(23.9 | 0);  // Result: 23
console.log(-23.9 | 0); // Result: -23

4)Format JSON Code

Lastly, you may have used JSON.stringify before, but did you realise it can also help indent your JSON for you?
The stringify() method takes two optional parameters: a replacer function, which you can use to filter the JSON that is displayed, and a space value.
The space value takes an integer for the number of spaces you want or a string (such as '\t' to insert tabs), and it can make it a lot easier to read fetched JSON data.

console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t'));
// Result:
// '{
//     "alpha": A,
//     "beta": B
// }'

No comments:

Post a Comment

Your feedback is always appreciated. I will try to reply to your queries as soon as time allows.Please don't spam,spam comments will be deleted upon reviews.