Skip to content
Advertisement

Printing 2 numbers before comma

I want to print numbers with precision to 2 digits before dot and 3 after.

Example:

JavaScript

will show:

JavaScript

I know that

JavaScript

will show me 3 digits after dot but how to get 2 digits before dot with 0 if that is shorter than 2 digits?

Advertisement

Answer

You can specify a total width for the output; if you include a leading 0 then the number will be padded with zeros to match that minimum width:

JavaScript

Demo:

JavaScript

Note that the number is a minimum width! If you need to truncate the floating point number itself, you’ll need to use slicing:

JavaScript

This will truncate string to remove characters from the start if longer than 6:

JavaScript

You may want to look at the format() function too; this function lets you apply the same formatting syntax as the str.format() formatting method and formatted string literals; the syntax is basically the same for floats:

JavaScript
Advertisement