Javascript добавить ведущие нули

Javascript добавить ведущие нули

Last updated: Jan 5, 2023
Reading time · 4 min

banner

# Add Leading Zeros to a Number in JavaScript

To add leading zeros to a number:

  1. Use the String() object to convert the number to a string.
  2. Call the padStart() method to add zeros to the start of the string.
  3. The padStart method will return a new string, padded with leading zeros.
Copied!
function padWithLeadingZeros(num, totalLength) return String(num).padStart(totalLength, '0'); > console.log(padWithLeadingZeros(3, 2)); // 👉️ "03" console.log(padWithLeadingZeros(3, 3)); // 👉️ "003" console.log(padWithLeadingZeros(3, 4)); // 👉️ "0003" console.log(padWithLeadingZeros(100, 2)); // 👉️ "100" // 👇️ Alternatively, simply use the Addition (+) operator const num = '00' + 3; console.log(num); // 👉️ "003"

The padWithLeadingZeros() function takes a number and its desired total length as parameters and pads the number with leading zeros if necessary.

The String.padStart method pads the current string with the provided string until the resulting string reaches the given length.

The padStart method takes the following 2 arguments:

Name Description
targetLength The string gets padded with the pad string up to this length.
padStart The string to pad the current string with.

The targetLength argument also takes into consideration decimal characters or a minus sign.

An easy way to think about the method is that it pads the original string to a target length with a supplied string.

Copied!
const num = 3; console.log(String(num).padStart(2, '0')); // 👉️ 03 console.log(String(num).padStart(3, '0')); // 👉️ 003 console.log(String(num).padStart(4, '0')); // 👉️ 0003

If you have a string of length 2 and you set the target length argument to 4 , the string will get padded with 2 leading zeros.

Copied!
// 👇️ "0022" console.log(String(22).padStart(4, '0'));

Make sure to convert the number to a string before using the padStart() method.

If you always want to pad the number with a specific number of leading zeros, use the number’s length to determine the target length.

Copied!
const num = 123; const str = String(num); // ✅ pad number with 2 leading zeros console.log(str.padStart(str.length + 2, '0')); // ✅ pad number with 3 leading zeros console.log(str.padStart(str.length + 3, '0'));

By adding n to the length of the number to determine the target length, we always add n leading zeros to the number.

If you convert the padded string back to a number, any of the leading zeros will automatically get dropped.

Copied!
const num = 3; const result = Number(String(num).padStart(5, '0')); console.log(result); // 👉️ 3

If the length of the number exceeds the provided target length, the entire string gets returned from the padStart method.

Copied!
function padWithLeadingZeros(num, totalLength) return String(num).padStart(totalLength, '0'); > const num = 123456; console.log(padWithLeadingZeros(num, 3)); // 👉️ "123456"

# Padding negative numbers with leading zeros

If you need to handle negative numbers, you need to add an if statement that adds the minus sign after the leading zeros have been added.

Copied!
function addLeadingZeros(num, totalLength) if (num 0) const withoutMinus = String(num).slice(1); return '-' + withoutMinus.padStart(totalLength, '0'); > return String(num).padStart(totalLength, '0'); > console.log(addLeadingZeros(3, 2)); // 👉️ "03" console.log(addLeadingZeros(-3, 3)); // 👉️ "-003"

We added an if statement to check if a negative number is provided to the function.

Note that we deliberately don’t include the minus sign in the target length for the new string.

To handle negative numbers, we just had to strip the minus, add the leading zeros and add the minus to the front of the string.

# Pad a number with leading zeros using the addition (+) operator

The addition (+) operator will convert the number to a string and will add the specified number of leading zeros to the beginning of the string.

Copied!
const positive = '00' + 5; console.log(positive); // 👉️ "005" const negative = '-' + '00' + String(-5).slice(1); console.log(negative); // 👉️ "-005"

When using the addition operator with a number and a string, the number gets converted to a string and the two strings get concatenated.

We used the same approach to handle negative numbers as we did with the padStart method.

If you have to pad a number with leading zeros often, define a reusable function.

Copied!
function padWithLeadingZeros(num, n) const char = '0'; return char.repeat(n) + num; > const num = 123; console.log(padWithLeadingZeros(num, 2)); // 👉️ 00123 console.log(padWithLeadingZeros(num, 3)); // 👉️ 000123 console.log(padWithLeadingZeros(num, 4)); // 👉️ 0000123

The padWithLeadingZeros function takes a number and how many leading zeros should be added to the number as parameters.

The function uses the String.repeat method to repeat the zero n times and adds it to the beginning of the string.

Copied!
console.log('0'.repeat(3)); // 👉️ "000" console.log('0'.repeat(2)); // 👉️ "00"

You can also use a while loop to add leading zeros to a number.

# Pad a number with Leading Zeros using a while loop

This is a three-step process:

  1. Convert the number to a string.
  2. Use a while loop to iterate for as long as the string hasn’t reached the target length.
  3. Pad the string with leading zeros until it reaches the target length.
Copied!
function padWithZero(num, targetLength) let str = String(num) while (str.length targetLength) str = '0' + str > return str > const num = 5; // ✅ pad with 2 leading zeros console.log(padWithZero(num, String(num).length + 2)); // 👉️ '005' // ✅ pad with 3 leading zeros console.log(padWithZero(num, String(num).length + 3)); // 👉️ '0005' // ✅ pad with 4 leading zeros console.log(padWithZero(num, String(num).length + 4)); // 👉️ '00005'

The padWithZero() function is very similar to the padStart method.

It takes a number and the desired target length as parameters and pads the number with leading zeros to the specified length.

The first step is to convert the number to a string.

The while loop iterates for as long as the string’s length is less than the desired target length.

On each iteration, we use the addition (+) operator to add a leading zero to the string.

Once the string reaches the desired target length, the condition in the while loop is no longer met.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Javascript добавить ведущие нули на сегодняшний день

Мне нужно указать дату с начальными нулями в компоненте day и month, добавив эти правила в script. Кажется, я не могу заставить его работать.

Как хорошее соглашение, вы должны в нижнем регистре первый символ в именах переменных и резервный верблюжий корпус для объектов / прототипов.

18 ответов

var MyDate = new Date(); var MyDateString; MyDate.setDate(MyDate.getDate() + 20); MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/' + ('0' + (MyDate.getMonth()+1)).slice(-2) + '/' + MyDate.getFullYear(); 

Чтобы объяснить, .slice(-2) дает нам последние два символа строки.

Итак, неважно, мы можем добавить «0» в день или месяц, и просто попросить последние два, так как они всегда те, которые мы хотим.

Итак, если MyDate.getMonth() возвращает 9 , это будет:

поэтому добавление .slice(-2) на этом дает нам два последних символа:

Но если MyDate.getMonth() возвращает 10 , это будет:

поэтому добавление .slice(-2) дает нам два последних символа или:

Может кто-нибудь объяснить, почему это лучше, чем ответ, который @Aleross дает ниже? Не сразу понятно, что он делает по сравнению с функцией pad, которая явно ясна.

Проще, просто используйте myDate.toISOString () с начальными нулями. Разобрать соответствующие части, используя подстроку.

@n00b n00b Я согласен. Это длиннее и кажется излишним. Кроме того, это выглядит хуже с точки зрения производительности (вызов slice после конкатенации выглядит дороже, чем простая конкатенация строк после сравнения), но я не выпускник информатики или что-то в этом роде. Это действительно креативное решение, но не более того, я думаю.

Путь умный. Хорошо работает для коротких, быстрых струн. Вероятно, хотите сделать что-то более производительное, если вы обрабатываете их много. В сценарии перетаскивания, перетаскивание и форматирование между несколькими метками даты / времени и отображение их на лету в движущемся окне — работает просто отлично.

@DazManCat: Это то, что он должен делать. Код начинается с добавления 20 дней к текущей дате. MyDate.setDate(MyDate.getDate() + 20);

@n00b n00b Полагаю, не обязательно лучше, просто популярнее. Я предполагаю, что если они будут расположены рядом, это будет связано с дополнительной частной функцией, необходимой для выполнения пэда.

@ n00b и @Phil Cooper, не зацикливаясь на рассуждениях о плюсах и минусах тайминга подпрограмм JavaScript, я обнаружил, что техника slice() в принятом ответе примерно на 1/10 секунды быстрее, чем @Aleross ‘ Техника s pad() на 1 миллион итераций. jsFiddle . «заплати свои деньги, сделай свой выбор».

Вот пример из Документов объектов даты в Mozilla Developer Network с использованием специальной функции «pad», без необходимости продления Javascript Number опытный образец. Удобной функцией, которую они дают в качестве примера, является

И ниже он используется в контексте.

/* use a function for the exact format desired. */ function ISODateString(d) < function pad(n)return d.getUTCFullYear()+'-' + pad(d.getUTCMonth()+1)+'-' + pad(d.getUTCDate())+'T' + pad(d.getUTCHours())+':' + pad(d.getUTCMinutes())+':' + pad(d.getUTCSeconds())+'Z' > var d = new Date(); console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z 

Очень хороший способ сделать это. Я думаю, что принятый ответ действительно хорош, но это даже чище, по моему мнению

@DavidFregoli, все эти функции даты в строку возвращают строку, поэтому, если вы вводите строку, pad выводит только строки.

Источник

Javascript добавить ведущие нули

Текстовые метки: javascript, js, format, number, int, leading zero, leading zeros, zero padding, padding

Запись: and-semakin/mytetra_data/master/base/1532936862yyohmv9gsm/text.html на raw.githubusercontent.com

При неизвестном количестве ведущих нулей:

При известном количестве (например, не более 10):

return (‘000000000’ + num).substr(-size);

  • How to make an AJAX call without jQuery?
  • JavaScript: setTimeout и setInterval
  • События DOM
  • Всплывающие модальные окна в JavaScript
  • Получить случайное число в указанном диапазоне на JavaScript
  • Вставка и удаление элементов из массива в JavaScript
  • Перевернуть строку в JavaScript
  • Цикл по массиву в JavaScript
  • Использование точки с запятой «;» в JavaScript
  • Комментарии в JavaScript
  • Отключение защиты в Chrome\Chromium
  • Извлечение переменной из localStorage со значением по умолчанию
  • Получить адрес страницы в JavaScript
  • Вывести число с ведущими нулями (leading zeros) в JavaScript
  • Конвертировать строку в число в JavaScript
  • Проверить, что массив существует и он не пуст в JavaScript
  • Конвертировать обычный объект в Map в JavaScript ES6
  • Операции над множествами в JavaScript
  • Создать глубокую копию многомерного массива в JavaScript
  • Сравнить два массива в JavaScript
  • Получить случайный элемент из массива в JavaScript
  • Проверить, что в массиве JavaScript есть элемент, удовлетворяющий условию
  • Получить список глобальных переменных в JavaScript
  • Вывести стек вызовов в JavaScript
  • Многострочные строки в JavaScript
  • Удалить свойство объекта в JavaScript
  • Конвертировать объект Map в массив в JavaScript
  • Отсортировать массив объектов по одному из полей объекта в JavaScript
  • throttle vs debounce
  • Общий подход к определению типа переменной в JavaScript
  • Заменить все вхождения подстроки в строке в JavaScript
  • Дополнить строку символами до нужной длины в JavaScript
  • Документирование JS-функций через JSDoc
  • Получить текущее время в миллисекундах в JavaScript
  • Проверить, что объект является промисом в JavaScript
  • Сгруппировать элементы массива по ключу в JS
  • Создать пустой объект без прототипа в JS
  • Закодировать строку для передачи через адресную строку в JS
  • Итерироваться по индексам и значениям массива (как enumerate в Python) в JS

Источник

Читайте также:  Java закончилась строка символов
Оцените статью