Converting number string to comma version - javascript

I have a Angular 2 / Typescript application string that contains number representations such as the following...
10000
10000.50
-10000
-10000.50
0
I want to add in commas after the thousand mark, for example...
10,000
10,000.50
-10,000
-10,000.50
0
What is the best way to do this?
I have tried some other answers but nothing is quite right.
For example this.value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); and this.value.toLocaleString(); don't seem to handle both the comman and decimal point.

Have you tried
var some_string_value = '-10000.50';
parseFloat(some_string_value).toLocaleString()
?

Use "indexOf('.')",splice to two part,then use the method you found.
function addComma(num){
//some type check here
var numStr = num.toString();
var intEnd = numStr.indexOf('.');
var onePart =numStr,otherPart ='';
if(intEnd !== -1){
var onePart = numStr.slice(0,intEnd);
var otherPart = numStr.slice(intEnd);
}
return onePart.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')+otherPart;
}

You can use a pipe, you can find a full answer to your question here: Add Comma Separated Thousands to Number Inputs in Angular2

Related

Format number to 2 decimal places only if it has decimal places

I want d3 to format my number to 2 decimal places, only if it has decimal value.
Also, I want it to work with one single format function.
For now, I have been using this. Is there any way I can improve this to be able to work around?
d3.format(",.2f")(10101); //10,101.00 which must be displayed as 10,000 only
d3.format(",.2f")(12334.2); //12,334.20 this is okay
I want it to work with one single format function
Well, that's not possible. D3 format functions cannot adapt to the number you pass to them like that.
However, you can have two format functions, and test to see if the number you're passing has or has not decimal places. This is one possible way to test:
number % 1
Which returns 0 for integers.
Then, in a ternary operator, you can choose which d3.format function you'll use:
!(number % 1) ? someFormat(number) : otherFormat(number)
Here is a demo:
var formatInteger = d3.format(",");
var formatDecimal = d3.format(",.2f");
var number1 = 10101;
var number2 = 12334.2;
function format(number){
return !(number % 1) ? formatInteger(number) : formatDecimal(number)
}
console.log(format(number1))
console.log(format(number2))
<script src="https://d3js.org/d3.v4.min.js"></script>
The closest you can get to that is if you use the '~' to remove any trailing zeroes. So in your case, the format would ',.2~f'.
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script>
console.log(d3.format(",.2~f")(10101));
console.log(d3.format(",.2~f")(12334.2));
</script>
More info about d3-format here: https://observablehq.com/#d3/d3-format
You can try this:
const formattedValue = value >= 100000
? value % 1 === 0
? SI(value).replace(".0", "")
: SI(value)
: value

remove all Decimals and single numbers from array / string

so my script generates a big blob of "Piano Notes" which are similar to...
var songNotes = "...";
the large Piano notes content
and my problem is between the piano notes which i need [also in the fiddle] there are empty ",," and decimal numbers.. so i cant figure out how to remove the empty
,, and decimals as big as
"1.0416666666642413,0.625,0,g3,1498.9583333333358,,0,c3,1.0416666666642413,0.625,0,c3"
and i want them removed except the the needed words which are
var theRightOnes = "s2,as2,cs3,ds3,fs3,gs3,as3,gs3,cs4,ds4,fs4,cs3,as4,gs4,ds5,a2,cs4,b2,c3,a3,ds4,b3,c4,as3,gs2,e3,c3,c4,cs3,ds3,a4,fs3,gs3,as3,g3,f3,b4,c5,a3,d4,as2,e4,g4,d3,b3,b2,f4,a2,d4,e4,cs5,gs1,e2,c2,c3,cs2,ds2,a3,fs2,gs2,as2,g2,f2,b3,c4,a2,d3,as1,e3,g3,d2,b2,b1,f3,a1,d5,e5";
so can anyone give me a clue on how this can be accomplished?
if anyone needs more info then i am ready oblige to do so..
Regards - Adarsh Hegde
var notesArr = songNotes.split(",");
var len = notesArr.length;
while(len--) {
if(!notesArr[len] || !isNaN(parseInt(notesArr[len], 10))) {
notesArr.splice(len, 1);
}
}
songNotes = notesArr.join(",");
I think you want to remove all the numbers from notes.
You can say like bellow
var notes = songNotes.split(",").filter(function(note){
return isNaN(note);
});
console.log(notes);
You can use Array.filter (see MDN) to weed out unwanted values:
var wantedNotes = songNotes.split(',')
.filter(function (v) {
return isNaN(+v) && v.trim().length
});
jsFiddle
just use regular expression,like this:
var a = "1.0416666666642413,0.625,0,g3,1498.9583333333358,,0,c3,1.0416666666642413,0.625,0,c3";
console.log(a.replace(/\b(\d+(\.\d+)?),+/g,""));

How to avoid parsing address as float in Javascript

I am working on javascript code that parses a tab delimited document. In order to facilitate searching I need to convert those properties that are a number to a float. However, mixed fields (like an address) should maintain the status of a String.
for(var i2=0;i2<line1.length;i2++){
var test = local[i2];
if(! (typeof test === 'undefined')){
test = test.trim();
};
var parsed = parseFloat(test);
if(!isNaN(parsed)){
if(line1[i2] === "Site Address")
console.log("Number before:"+local[i2]+" After:"+parsed);
object[line1[i2]]=parsed;
}
else{
if(line1[i2] === "Site Address")
console.log("before:"+local[i2]+" After:"+test);
object[line1[i2]]=test;
}
}
This seems to work ok unless there are both numbers and chars like the following....
Number before:1752 E MAIN ST After:1752
Is there a way to do this where the above is not seen as explicitly a number?
You can use the unary + operator:
var parsed = +test;
The parseFloat() function is OK with strings that start with a valid number that's followed by non-numeric stuff, as you've discovered.
If that seems too "hackery" you can also use the Number constructor:
var parsed = Number( test );
You haven't provided very much test data, so answers may not be very good. You can try using a regular expression so that only things that look like numbers are treated as numbers, e.g.
var isNum = /^\d+(\.\d+)?$/;
var test = line1[i2];
parsed = isNum.test(test)? parseFloat(test) : test;
The variable "test" would probaby be better named "item" or "value" or similar.

JavaScript add decimal without using toFixed() method

I've got some values that are appended with 00's for cents by PHP. I need to add a decimal point to them.
val = 10000 (needs to turn into 100.00);
val.toFixed(2) = 10000.00 (no bueno);
val.magic() = 100.00 (perf!)
Thanks!
(val/100).toFixed(2) = 100.00;
If you have a string value in cents, a simple regular expression can be used to insert a decimal point:
function addPoint(s) {
return s.replace(/(\d\d)$/,'.$1');
}
var s = '1000';
alert(addPoint(s)); // 10.00

How to append an extra 'Zero' after decimal in Javascript

Hye,
Iam new to javascript working with one textbox validation for decimal numbers . Example format should be 66,00 .but if user type 66,0 and dont type two zero after comma then after leaving text box it should automatically append to it .so that it would be correct format of it . How can i get this .How can i append ?? here is my code snippet.
function check2(sender){
var error = false;
var regex = '^[0-9][0-9],[0-9][0-9]$';
var v = $(sender).val();
var index = v.indexOf(',');
var characterToTest = v.charAt(index + 1);
var nextCharAfterComma = v.charAt(index + 2);
if (characterToTest == '0') {
//here need to add
}
}
Use .toFixed(2)
Read this article: http://www.javascriptkit.com/javatutors/formatnumber.shtml
|EDIT| This will also fix the issue if a user types in too many decimals. Better to do it this way, rather than having a if to check each digit after the comma.
.toFixed() converts a number to string and if you try to convert it to a float like 10.00
then it is impossible.
Example-
10.toFixed(2) // "10.00" string
parseFloat("10.00") // 10
Number("10.00") // 10

Categories

Resources