Добавить .00 (toFixed), только если число меньше двух знаков после запятой
Мне нужно добавить нули, так что каждое число имеет как минимум два десятичных знака, но без округления. Так, например:
5 --> 5.00
5.1 --> 5.10
5.11 --> 5.11 (no change)
5.111 --> 5.111 (no change)
5.1111 --> 5.1111 (no change)
В моей функции отсутствует IF для проверки менее двух знаков после запятой:
function addZeroes( num ) {
var num = Number(num);
if ( //idk ) {
num = num.toFixed(2);
}
return num;
}
Спасибо!
Проводка альтернативного ответа, в дополнение к двум ниже. (Имейте в виду, что я не эксперт, и это просто для ввода текста, а не для синтаксического анализа сложных значений, таких как цвета, которые могут иметь проблемы с плавающей запятой и т.д.)
function addZeroes( value ) {
//set everything to at least two decimals; removs 3+ zero decimasl, keep non-zero decimals
var new_value = value*1; //removes trailing zeros
new_value = new_value+''; //casts it to string
pos = new_value.indexOf('.');
if (pos==-1) new_value = new_value + '.00';
else {
var integer = new_value.substring(0,pos);
var decimals = new_value.substring(pos+1);
while(decimals.length<2) decimals=decimals+'0';
new_value = integer+'.'+decimals;
}
return new_value;
}
[Это не дублирующий вопрос. Вопрос, который вы связываете, предполагает "знание, что у них есть как минимум 1 десятичный знак". Десятичные точки не могут приниматься в текстовых вводах, и это делало ошибки.]
Ответы
Ответ 1
Ну вот:
function addZeroes(num) {
// Convert input string to a number and store as a variable.
var value = Number(num);
// Split the input string into two arrays containing integers/decimals
var res = num.split(".");
// If there is no decimal point or only one decimal place found.
if(res.length == 1 || res[1].length < 3) {
// Set the number to two decimal places
value = value.toFixed(2);
}
// Return updated or original number.
return value;
}
// If you require the number as a string simply cast back as so
var num = String(value);
Смотрите обновленную скрипку для демонстрации.
http://jsfiddle.net/jhKuk/159/
Ответ 2
Следующий код обеспечивает один из способов сделать то, что вы хотите. Есть и другие.
function addZeroes( num ) {
// Cast as number
var num = Number(num);
// If not a number, return 0
if (isNaN) {
return 0;
}
// If there is no decimal, or the decimal is less than 2 digits, toFixed
if (String(num).split(".").length < 2 || String(num).split(".")[1].length<=2 ){
num = num.toFixed(2);
}
// Return the number
return num;
}
http://jsfiddle.net/nzK4n/
alert(addZeroes(5)); // Alerts 5.00
alert(addZeroes(5.1)); // Alerts 5.10
alert(addZeroes(5.11)); // Alerts 5.11
alert(addZeroes(5.111)); // Alerts 5.111
Ответ 3
Может быть, использовать .toLocaleString()
:
var num = 5.1;
var numWithZeroes = num.toLocaleString("en",{useGrouping: false,minimumFractionDigits: 2});
console.log(numWithZeroes);
Как функция/демо:
function addZeroes(num) {
return num.toLocaleString("en", {useGrouping: false, minimumFractionDigits: 2})
}
console.log('before after correct');
console.log('5 ->', addZeroes(5) , ' --> 5.00');
console.log('5.1 ->', addZeroes(5.1) , ' --> 5.10');
console.log('5.11 ->', addZeroes(5.11) , ' --> 5.11 (no change)');
console.log('5.111 ->', addZeroes(5.111) , ' --> 5.111 (no change)');
console.log('5.1111 ->', addZeroes(5.1111) , '--> 5.1111 (no change)');
console.log('-5 ->', addZeroes(-5) , ' --> -5.00');
Ответ 4
Вот функция, которая будет делать это, функция ожидает число
var addZeroes = function(num) {
var numberAsString = num.toString();
if(numberAsString.indexOf('.') === -1) {
num = num.toFixed(2);
numberAsString = num.toString();
} else if (numberAsString.split(".")[1].length < 3) {
num = num.toFixed(2);
numberAsString = num.toString();
}
return numberAsString
};
Ответ 5
Для текстового поля типа номера
Добавить .00 при наличии номера
function addZeroes(ev) {
debugger;
// Convert input string to a number and store as a variable.
var value = Number(ev.value);
// Split the input string into two arrays containing integers/decimals
var res = ev.value.split(".");
// If there is no decimal point or only one decimal place found.
if (res.length == 1 || res[1].length < 3) {
// Set the number to two decimal places
value = value.toFixed(2);
}
// Return updated or original number.
if (ev.value != "") {
ev.value = String(value);
}
}
<input type="number" step=".01" onchange="addZeroes(this)" />
Ответ 6
decimalNumber = number => Number.isInteger(number) ? number.toFixed(2) : number