Add decimal point to last character

I am writing something that pulls some data from the Internet; the fact is that one of the keys to the object that I receive has weight and height and well, they are not formatted; they are as a whole; now for example; if I get a key weightwith a value 1000, which means that it is 100.0 kg; not only 1000, the same with height, but sometimes I can get something like 10on height, which is 0.99m or 1m; 100is 10.0 m, etc., so my question is: what can I do here to format these values, correctly adding .0to final if the value does not have it, and if it really just adds the decimal point to the last character? I tried to do it ifs, but they were hardcoded and I look really bad, plus it didn’t work.

The result that I get

Example:

Weight: 1000
Height: 20

Weight: 69
Height: 7

Weight: 432
Height: 12

Expected Result:

Weight: 100.0
Height: 2,0

Weight: 6.9
Height: 0.7

Weight: 43.2
Height: 1.2
+4
source share
1 answer

You can divide by 10and use Number#toFixednumbers to format.

The method toFixed()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);
Run codeHide result
+4
source

Source: https://habr.com/ru/post/1664865/


All Articles