I have scenario where if user enters for example 000.03, I want to show the user it as .03 instead of 000.03. How can I do this with Javascript?
You can use a regular expression:
"000.03".replace(/^0+\./, ".");
Adjust it to your liking.
This actually is trickier than it first seems. Removing leading zero's is not something that is standard Javascript. I found this elegant solution online and edited it a bit.
function removeLeadingZeros(strNumber)
{
while (strNumber.substr(0,1) == '0' && strNumber.length>1)
{
strNumber = strNumber.substr(1);
}
return strNumber;
}
userInput = "000.03";
alert(removeLeadingZeros(userInput));
How about:
function showRounded(val) {
var zero = parseInt(val.split('.')[0],10) === 0;
return zero ? val.substring(val.indexOf('.')) : val.replace(/^0+/,'') );
}
console.log(showRounded('000.03')); //=> ".03"
console.log(showRounded('900.03')); //=> "900.03"
console.log(showRounded('009.03')); //=> "9.03"
Or adjust Álvaro G. Vicario's solution to get rid of leading zero's into:
String(parseFloat("090.03")).replace(/^0+\./, ".")
This function will take any string and try to parse it as a number, then format it the way you described:
function makePretty(userInput) {
var num,
str;
num = parseFloat(userInput); // e.g. 0.03
str = userInput.toString();
if (!isNaN(num) && str.substring(0, 1) === '0') {
str = str.substring(1); // e.g. .03
} else if (isNaN(num)) {
str = userInput; // it’s not a number, so just return the input
}
return str;
}
makePretty('000.03'); // '.03'
makePretty('020.03'); // '20.03'
It you feed it something it cannot parse as a number, it will just return it back.
Update: Oh, I see If the single leading zero needs to be removed as well. Updated the code.
Assuming your input's all the same format, and you want to display the .
user = "000.03";
user = user.substring(3);
You can convert a string into a number and back into a string to format it as "0.03":
var input = "000.03";
var output = (+input).toString(); // "0.03"
To get rid of any leading zeroes (e.g. ".03"), you can do:
var input = "000.03";
var output = input.substr(input.indexOf(".")); // ".03"
However, this improperly strips "20.30" to ".30". You can combine the first two methods to get around this:
var input = "000.03";
var output = Math.abs(+input) < 1 ?
input.substr(input.indexOf(".")) :
(+"000.03").toString();
Related
I want to remove the decimals after a price if it ends on ',00'. If it ends on anything else it should remain. I'll have to be able to see on what the price ends to do so, but how do I achieve this in Javascript?
My idea was checking if the price ended on 00 and removing it in an if statement.
function gformFormatMoney(text, isNumeric){
if(!gf_global.gf_currency_config)
return text;
var currency = new Currency(gf_global.gf_currency_config);
var unformatted = currency.toMoney(text, isNumeric);
var formatted;
var formatting = unformatted%10;
if(formatting == 00) {
}
return unformatted;
}
^This gives a error 'Octal litterals with the prefix 0 are not allowed'
You need to parse your numbers as a float, fix it to 2 decimals (in all cases), and remove any matches for (.00). Something like this could work:
function fixFloat(num){
return parseFloat(num).toFixed(2).replace('.00', '');
}
console.log(fixFloat(20.00));
console.log(fixFloat(40.40));
console.log(fixFloat(30.01));
Please be aware that this will return a string. If you wish to convert this back to a number, you'll need to parse it again.
You should use toFixed.
as for :
let num = 50.00;
num.toFixed(2).includes('.00') ? num.toFixed() :num.toFixed(2);
If the data type is not string , the trailing zeros after decimal will be removed. If it is a string use parseInt to convert to number
let price = 20.00;
console.log(price)
let price1 = '40.00'
console.log(parseInt(price1, 10))
let price2 = '40.00'
console.log(parseFloat(price2, 10))
Turns out it wasn't an integer, but a string.
I fixed it by doing:
function gformFormatMoney(text, isNumeric){
if(!gf_global.gf_currency_config)
return text;
var currency = new Currency(gf_global.gf_currency_config);
var unformatted = currency.toMoney(text, isNumeric);
var formatted = unformatted.replace(',00', '');
return formatted;
}
I want to remove decimal from number in javascript:
Something like this:
12 => 12
12.00 => 1200
12.12 => 1212
12.12.12 => error: please enter valid number.
I can not use Math.round(number). Because, it'll give me different result. How can I achieve this? Thanks.
The simplest way to handle the first three examples is:
function removeDecimal(num) {
return parseInt(num.toString().replace(".", ""), 10);
}
This assumes that the argument is a number already, in which case your second and fourth examples are impossible.
If that's not the case, you'll need to count the number of dots in the string, using something like (trick taken from this question):
(str.match(/\./g) || []).length
Combining the two and throwing, you can:
function removeDecimal(num) {
if ((num.toString().match(/\./g) || []).length > 1) throw new Error("Too many periods!");
return parseInt(num.toString().replace(".", ""), 10);
}
This will work for most numbers, but may run into rounding errors for particularly large or precise values (for example, removeDecimal("1398080348.12341234") will return 139808034812341230).
If you know the input will always be a number and you want to get really tricky, you can also do something like:
function removeDecimal(num) {
var numStr = num.toString();
if (numStr.indexOf(".") === -1) return num;
return num * Math.pow(10, numStr.length - numStr.indexOf(".") - 1);
}
You can use the replace method to remove the first period in the string, then you can check if there is another period left:
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
// invalid input
}
Demo:
function reformat(str) {
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
return "invalid input";
}
return str;
}
// show in Stackoverflow snippet
function show(str) {
document.write(str + '<br>');
}
show(reformat("12"));
show(reformat("12.00"));
show(reformat("12.12"));
show(reformat("12.12.12"));
How about number = number.replace(".", ""); ?
I'm starting to learn javascript and I basically needed a countup that adds an x value to a number(which is 0) every 1 second. I adapted a few codes I found on the web and came up with this:
var d=0;
var delay=1000;
var y=750;
function countup() {
document.getElementById('burgers').firstChild.nodeValue=y+d;
d+=y;
setTimeout(function(){countup()},delay);
}
if(window.addEventListener){
window.addEventListener('load',countup,false);
}
else {
if(window.attachEvent){
window.attachEvent('onload',countup);
}
}
There's probably residual code there but it works as intended.
Now my next step was to divide the resultant string every 3 digits using a "," - basically 1050503 would become 1,050,503.
This is what I found and adapted from my research:
"number".match(/.{1,3}(?=(.{3})+(?!.))|.{1,3}$/g).join(",");
I just can't find a way to incorporate this code into the other. What should I use to replace the "number" part of this code?
The answer might be obvious but I've tried everything I knew without sucess.
Thanks in advance!
To use your match statement, you need to convert your number to a String.
Let's say you have 1234567.
var a = 1234567;
a = a + ""; //converts to string
alert(a.match(/.{1,3}(?=(.{3})+(?!.))|.{1,3}$/g).join(","));
If you wish, you can wrap this into a function:
function baz(a) {
a = a + "";
return a.match(/.{1,3}(?=(.{3})+(?!.))|.{1,3}$/g).join(",");
}
Usage is baz(1234); and will return a string for y our.
While I do commend you for using a pattern matching algorithm, this would probably be easier to, practically speaking, implement using a basic string parsing function, as it doesn't look anywhere as intimidating from just looking at the match statement.
function foo(bar) {
charbar = (""+bar).split(""); //convert to a String
output = "";
for(x = 0; x < charbar.length; x++) { //work backwards from end of string
i = charbar.length - 1 - x; //our index
output = charbar[i] + output; //pre-pend the character to the output
if(x%3 == 2 && i > 0) { //every 3rd, we stick in a comma, except if it is not the leftmost digit
output = ',' + output;
}
}
return output;
}
Usage is basically foo(1234); which yields 1,234.
I'm trying to validate a form input value. The function below states is the value of the input is a number below 150, show error. Works as it should. However, I want to add to it. If the value contains ANYTHING other than a numeric value AND/OR is a value under 150, show error...
How can I modify?
if ($('.billboard-height').val() < 150) {
$('.sb-billboardalert').fadeIn(600);
}
Since your more thorough validation should be on the server-side anyway, you could just use parseInt or parseFloat depending on what sort of value you are expecting. Then check if the result is actually a number and that it also meets your constraints:
var number = parseFloat($('.billboard-height').val()); // or parseInt depending on expected input
if (isNaN(number) || number < 150) {
$('.sb-billboardalert').fadeIn(600);
}
EDIT:
Based on your comments, you are entering regex land. I gather you only ever want a natural number (and the way parseInt/parseFloat ignores trailing non-numeric characters like px, em, etc. is not ok). How about:
var val = $('.billboard-height').val();
var number = parseInt(val, 10);
if ( ! val.match(/^[0-9]{3,4}$/) || number < 150) {
$('.sb-billboardalert').fadeIn(600);
}
This should only allow natural numbers 150-9999.
I would suggest using regexes:
var intRegex = /^\d+$/;
var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;
var str = $('#myTextBox').val();
if(intRegex.test(str) || floatRegex.test(str)) {
alert('I am a number');
...
}
Or with a single regex as per #Platinum Azure's suggestion:
var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
var str = $('#myTextBox').val();
if(numberRegex.test(str)) {
alert('I am a number');
...
}
ref: checking if number entered is a digit in jquery
Don't forget the radix parameter in parseInt():
if (parseInt($('.billboard-height').val(), 10) < 150) {
It's probably faster than using a regex. Regular expressions are not known for being fast, but they are very powerful. It might be overkill for this scenario.
You can try out HTML5's built in form validation:
<input type="number" min="150">
browser support is still pretty shakey though
Any value from an input or select will be a string in javascript. You need to use parseInt() to use operators like > or <. == can be used if you use it to compare to a string like if ($('.billboard-height').val() == "150")
Try parseInt and isNaN functions for check if value is number and less than 150:
var intVal = parseInt($('.billboard-height').val());
if(!isNaN(intVal)){ //not Number
if (parseInt($('.billboard-height').val()) < 150) { //not less than 150
$('.sb-billboardalert').fadeIn(600);
}
}
If you need to support floating point numbers, you can check if a variable is valid using:
function isNumber (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var val = $('.billboard-height').val();
if (isNumber(val) && parseFloat(val) < 150) {
$('.sb-billboardalert').fadeIn(600);
}
If you only need to support integers, use parseInt(n, 10), where 10 is the base to convert the string to.
var val = parseInt($('.billboard-height').val(), 10);
if (val && val < 150) {
$('.sb-billboardalert').fadeIn(600);
}
// Displays an alert if s contains a non-numeric character.
function alertForNonNumeric(s) {
var rgx = /[^0-9]/;
if (s.search(rgx) !== -1) {
alert("Input contains non-numeric characters!");
}
}
JS Fiddle here
NOTE: If you want to check for negative ints as well, you can add a minus sign to the regex:
function alertForNonNumeric(s) {
var rgx = /[^0-9-]/;
if (s.search(rgx) !== -1) {
alert(s + " contains non-numeric characters!");
}
}
I use this solution, I find it quite ellegant - no alerts, user is effectively unable to enter non numeric characters.
This is jQuery example:
function digitsOnly(){
// extract only numbers from input
var num_val = $('#only_numbers').val().match(/\d+/);
$('#only_numbers').val(num_val);
}
Your html:
<input type="text" name="only_numbers" id="only_numbers" on oninput="digitsOnly();"/>
I looked through here last night for some examples on adding leading zeroes with JavaScript and I couldn't get any of them to work for my purposes. I want to do this with the data once you hit the submit button. It is running a set of checkers when it does this and this is what I have included, but I grab the POST data in a test php page and the field I am trying to fix shows "undefined"
I need the number of digits to always be 7, regardless of whether they entered a four or five digit number. Leading zeroes need to be added. Not sure if I am kind of close or way off target with this:
function pad(number, length){
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
}
offidlength = custform.optionaldata10.value.length;
if (offidlength <7) {
custform.optionaldata10.value = pad(custform.optionaldata10.value, 7);
}
You forgot the return statement.
return str;
Should be at the end of the function.
edit function should look like:
function pad(number, length){
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
You can make your expression simpler, if you always want 7 digits-
var offid= custform.optionaldata10.value, L= 7-offid.length;
if(L>0) custform.optionaldata10.value= '0000000'.substring(0, L)+offid;