Dotdeb
Dotdeb

Reputation: 43

Add decimal point to the last character

I'm writing something that pulls some data from the internet; the thing is that one of the keys from the object that I get has weight and height and well, they're not formatted; they're like a whole integer; now, for example; if I get a weight key with a value of 1000 that means that it is 100.0kg; not just 1000, same with the height but sometimes I can get something like 10 on height which is 0.99m or 1m; 100 is 10.0m and so on, so, my question is; what can I do here to format these values properly adding a .0 to the final if the value doesn't have it and if it does have it just add the decimal point before the last character? I tried doing some ifs but they were hard coded and I looking very bad, plus it didn't work.

Output that I'm getting

Example:

Weight: 1000
Height: 20

Weight: 69
Height: 7

Weight: 432
Height: 12

Expected output:

Weight: 100.0
Height: 2,0

Weight: 6.9
Height: 0.7

Weight: 43.2
Height: 1.2

Upvotes: 4

Views: 833

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386604

You could divide by 10 and use Number#toFixed for formatting a number.

The toFixed() method formats a number using fixed-point notation.

var values = [1000, 20, 69, 7, 432, 12];

values = values.map(function (v) {
    return (v / 10).toFixed(1);
});

console.log(values);

Upvotes: 4

Related Questions