Add Comma after thousand number not for decimal numbers - javascript

I am adding a comma to thousand number but those numbers have decimal value so that decimal value also added comma which I don't want
Eg: default number 2476.570550272 and I want to add comma 2,476.570550272
After using the below code I am getting comma to decimal number also like this 2,476.570,550,272.
$.fn.digits = function () {
return this.each(function () {
$(this).text($(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
})
}
$(".number").digits();

Javascript has a function for this, it's called NumberFormat:
const number = 123456.789123123123;
const yourFormat = new Intl.NumberFormat('en-EN',{ maximumFractionDigits: 5 });
console.log(yourFormat.format(number));
The function is very versatile, here you can find more options. I suggest a read for what it can do for future usage also. It has many options and is also very recommendable for currencies.

Try with this.
function numberWithCommas(ADD-YOUR-NUM-HERE) {
var parts = number.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}

Here's a vanilla-flavored adaptation of your regex that works as you specified.
digits(document.querySelectorAll(".numInput"));
function digits(inputs){
for(let input of inputs){
const [int, dec] = input.value.split(".");
input.value = int.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + (dec ? "."+dec : "");
}
}
<input class="numInput" value="4321.09876" />
<input class="numInput" value="987654321" />
<input class="numInput" value=".123456789" />

Related

How to remove the leading zeros in the number inside input type='number'? [duplicate]

This question already has answers here:
Remove/ truncate leading zeros by javascript/jquery
(17 answers)
Closed 19 days ago.
I am a beginner in React JS. I have a use case in that I want to correct the number that a user enters in <input type='number> field.
By default, a user can enter numbers with leading zeros like 0002 or -0042, etc.
I want to make it such that the leading zeros are removed when the user enters the number. Also, the user should be able to enter decimal as well as negative numbers. I have done it using onBlur but I want to somehow do it onChange method itself.
onChange=()=>{ ... }
<input type = 'number' onChange={onChange}>
I want to make it such that the leading zeros are removed when the user enters the number.
You can remove the leading zeros with String.replace:
// ... code that obtains the user input in `inputText` ...
inputSanitisedText = inputText.replace(/^0+/, '')
(I am assuming you don't want to change the user's input while they're entering it. That would be very bad UI design.)
You can use regex to remove zeros from beginning: /^0+/
In your case:
onChange = (e) => {
const _removedZeros = e.target.value.replace(/^0+/, '')
///...
}
you can simply multiplied value to 1, like this :
const [value, setValue] = useState("");
<input
value={Boolean(value) ? value : ''}
type="number"
onChange={(e) => setValue(e.target.value * 1)}
/>
in this way user cannot type leading zeros
As per your description, you can solve this by using the parseFloat() function. This function will remove the leading zeros and will convert the input value to a decimal/fractional number.
The code should be like this:
const onChange = (event) => {
const value = parseFloat(event.target.value);
event.target.value = isNaN(value) ? '' : value;
};
something like this?
foo.oninput = (e) => {
const value = foo.value;
let [_, sign, integer, decimals] = value.replace(/[^\d\.\-]/g, "") // invalid characters
.replace(/(\..*?)\./g, "$1") // multiple dots
.replace(/(.+)-/g, "$1") // invalid signs
.match(/^(-?)(.*?)((?:\.\d*)?)$/);
let pos = foo.selectionStart - 1;
if(!integer && decimals) pos += 2;
// don't convert an empty string into a 0,
// unless there are decimal places following
if(integer || decimals) {
integer = +integer;
}
const formatted = sign + integer + decimals;
if(formatted !== value) {
foo.value = formatted;
foo.setSelectionRange(pos, pos);
}
}
<input type="text" id="foo" />

Match only numbers including decimals [duplicate]

This question already has answers here:
Decimal or numeric values in regular expression validation
(13 answers)
Closed 2 years ago.
I have an input field I want the input value to be only numbers and decimals nothing more but the problem is that when I type the Unicode characters and letters and semicolons the input value excepts it how do I achieve that.
let newValue = item.value.replace(new RegExp(/[a-z] && [#!#$%^&*()_+}{}|:,=] /,'ig'), "");
item.value = newValue;
If you want to only accept number and decimals for your input you can do either of these two ways:
Use input type number.
<input type="number"/>
Use a regex like below, which accept only numbers and decimals:
^-?[0-9]\d*(\.\d+)?$
NOTE: If you want to use the comma (and . in any place) as input also, you can use this one (according to this post):
^-?[0-9][\.\d]*(,\d+)?$
Update
Validation on input:
var org = '';
document.getElementsByTagName('input')[0].oninput = function(e) {
var val = document.getElementsByTagName('input')[0].value;
if(val == '' || val.match(/^([0-9]*\.)?[0-9]*$/)) {
org = val;
} else {
val = org;
}
document.getElementsByTagName('input')[0].value = val;
}
document.getElementsByTagName('input')[0].oninput();
Number here: <input value="1.23" type="text" /><br />
function scrubInput() {
let numberInputElem = document.getElementById('numberInput');
const regex = /[^0-9\.]/
let newValue = numberInputElem.value.replace(regex, "");
numberInputElem.value = newValue;
}
<input type="text" id="numberInput" oninput="scrubInput()"/>

JavaScript Regex: When input field onChange event fires, format fields

I am using react 16.8.2 new hooks API. -Just for info-
My problem only involves JS.
I have two input fields. They take only numbers as inputs. If the user enters /\D+/ (non-digits), the field is set to ''(empty). If he enters 2.3393, the number should always be rounded to two decimal places 2.34
Field1: onChange formats the number to $ 32,233,233,322.24
Field2: onChange formats the number to 99%. Decimals places are simply truncated.
The Input field should be able to handle e.nativeEvent.inputType deleteContentBackward as well. Such that if the user is at $ 2 and deletes 2, Field1 becomes empty. Similarly for Field2. 1% on deleting % becomes empty.
So far I have this:
const handleInputChange = function (e) {
const val = e.target.value;
const formatValue = function () {
if (/.*\d?\.\d*/.test(val)) return val.replace(/(?<=\d?\.\d*)\..*/g, '');
return +val.replace(/\$\s?|(,+)|%/g, '');
};
if (formatValue()) {
if (fieldSuffix === 'Percentage') {
if (e.nativeEvent.inputType === 'deleteContentBackward') return setVal(`${formatValue()}%`.replace(/^\d%$|\d(?=%)/, ''));
return setVal(`${formatValue()}%`);
}
if (fieldSuffix === 'Dollars') return setVal(`$ ${formatValue()}`.replace(/\B(?=(\d{3})+(?!\d))/g, ','));
return setVal(formatValue());
}
return setVal('');
};
return (
<input
value={val}
onChange={handleInputChange}
/>
)
It does not work well for when user enters single .. $ are prepend for every . keystroke. The case that when user enters /\D+/ is not handled. % Field2 decimal place truncation case is also not handled. I can think of other cases also that are not handled.
My code is getting complicated. This approach is not elegant. Please Help.
The following code works well.
const handleInputChange = function (e) {
const formatValue = function () {
// Remove non-digit, except '.' and remove everything beginning from second decimal '.'
return e.target.value.replace(/[^0-9.]|(?<=^[^.]*\.[^.]*)\..*/g, '');
};
if (formatValue()) {
if (fieldSuffix === 'Percentage') {
// Percentage decimal truncated
const truncatedPercentage = formatValue().replace(/\..*/, '');
if (e.nativeEvent.inputType === 'deleteContentBackward') return setVal(`${formatValue()}%`.replace(/^\d%$|(\d|\.)(?=%)/, ''));
return setVal(`${truncatedPercentage}%`);
}
if (fieldSuffix === 'Dollars') {
// Truncated to two decimal places, not rounded
const truncatedDollar = formatValue().replace(/(?<=\.\d{2}).*/, '');
// Format and insert ','
return setVal(`$ ${truncatedDollar}`.replace(/\B(?=(\d{3})+(?!\d))/g, ','));
}
}
return setVal('');
};
I still feel that there is a lot of redundancy and unhandled cases in this code

Can I check on what an integer ends in Javascript

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;
}

Using Decimals in React Native

I have a state as value: 10.00 and once I update it with some operation and add it to a <Text> the ".00" part gets trimmed off. If it was a value like 10.50, it'll be displayed as 10.5
This is a issue as I want to display currency values. How to handle this?
Found the answer. To have the value with decimal values, use toFixed() method.
Example:
var value = 10;
value = value.toFixed(2);
this.setState({subTotal: value});
The output would be: 10.00
here is another solution you can also try, what i need is don't allow to enter more than 2 decimal digits (after decimal point) and also shouldn't allow more than two decimal points or any other character.
ConTwoDecDigit=(digit)=>{
return digit.indexOf(".")>0?
digit.split(".").length>=2?
digit.split(".")[0]+"."+digit.split(".")[1].substring(-1,2)
: digit
: digit
}
<TextInput
value={this.state.salary}
onChangeText={value => this.setState({ salary: this.ConTwoDecDigit(value) })}
keyboardType={'decimal-pad'}
/>
An alternative to the verified answer which catches more edge cases and allows string inputs. (defaults to 2dp but can be set by function caller)
export function normaliseValue (value: string, decimals = 2) {
if (!value) {
return ''
}
if (value === '.') {
return value = '0.'
}
var regex = new RegExp(`^-?\\d+(?:\\.\\d{0,${decimals}})?`)
const decimalsNumber = value.toString().match(regex)[0]
const parsed = parseFloat(decimalsNumber).toFixed(2)
if (isNaN(parsed)) {
return '0'
}
return parsed
}
Example use in code:
<TextInput
label='Hours worked'
placeholder='Hours worked'
keyboardType='decimal-pad'
value={String(values.hours)}
onChangeText={(val) => setFieldValue('hours', normaliseValue(val, 3))}
/>

Categories