Ian - 5 months ago 19

Javascript Question

I have a script that generates a number and sets it to a textbox. If, for example, the number was 6.3, I'd want to be able to convert this into 6 years 4 months.

Is there a quick way to do this?

Answer

```
var n = 6.3;
var y = Math.floor(n); // whole years
var m = Math.floor(12 * (n - y)); // treat remainder as fraction of a year
```

I note that this gives 3 for the month, not 4. Why do you think 6.3 should give 4 months? 6 years and 4 months is 6.333333 years.

Source (Stackoverflow)

Comments