Convert percent into a decimal in html/ javascript - javascript

Javascript:
var validate(s) = s.match ^( 100(?:\.0{1,2})? | 0*?\.\d{1,2} | \d{1,2}(?:\.\d {1,2})? )% $ != null;
var str = value.match(/\/\/%//g);
if(converted==NaN){
alert('Input was not a number');
}
else if(converted != null) {
var fracToDecimal = eval (value);
alert(fracToDecimal);
}
else if(converted = str) {
var percToDecimal = value/100;
alert(percToDecimal);
} }

So you have a string like: 50%? How about:
var percent = "50%";
var result = parseFloat(percent) / 100.0;

If you use parseFloat, it will read the string up until the first non-number character (the %)
var x = '20.1%';
var y = parseFloat(x); // 20.1
Then you can check if it's NaN, and convert it.
if(!isNaN(y)){
y /= 100; // .201
}
Note: You need to use isNaN because NaN === NaN is false (JavaScript is weird).
UPDATE: I see you also have fracToDecimal in there. You don't need eval for that. Just do a simple split.
var frac = '1/2';
var nums = frac.split('/');
var dec = nums[0]/nums[1];

Assuming the "%" is on the right hand of the string, just use parseFloat(s)/100
http://jsfiddle.net/TrCYX/1/

I'm very late, but keeping it as itself if it is a decimal goes like this
let val = "100%"
String(val).includes("%") ? parseFloat(val)/100 : parseFloat(val) //1
val = 1 //or val = "1"
String(val).includes("%") ? parseFloat(val)/100 : parseFloat(val) //1

function convertToDecimal(percent) {
let newarr =[]
for(i=0; i<percent.length; i++) {
const parsed = parseFloat(percent[i]);
if (!Number.isNaN(parsed[i])) {
let newval = parseFloat(percent[i]) / 100;
//return newval;
newarr.push(newval)
} else {
return 0;
}
} return newarr;
}
console.log(convertToDecimal(["33%", "98.1%", "56.44%", "100%"]))

Related

How to change (manipulate) char string depend on giving value

i want to ask how to manipulate char in string depends on giving value
my string
"---x---x---x------x"
when im input a value = 2
char "x" was changed to "o" in 2 times
my expected value is
"---o---o---x------x"
thank you in advance
based on solution here:
var str = "---x---x---x------x"
var n = 0
var N = 2
var newStr = str.replace(/x/g,s => n++<N ? 'o' : s)
const x = "---x---x---x------x";
let input = 2;
let output = [];
for (const dashes of x.split("x")) {
output.push(dashes);
if (input > 0) {
input--;
output.push("o");
} else {
output.push("x");
}
}
output.pop();
output = output.join("");
console.log({ output });
You can just loop over the and replace x with o until value becomes 0(which is falsy value)
let str = "---x---x---x------x";
let value = 2;
while (value--) {
str = str.replace("x", "o");
}
console.log(str);

How to set auto 2 decimal number using value from id input type="text" javascript?

How to set auto 2 decimal number using value from id input type="text" javascript ?
http://jsfiddle.net/A4wxX/90/
First , fill data eg: 2 into input , it's will update input to 2.00
But not work When i user this
var numb = document.getElementById("int").value;
How can i do ? thank.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script type="text/javascript">
function fn_do() {
var numb = document.getElementById("int").value;
//var numb = 123;
var zzz = numb.toFixed(2);
document.getElementById("int").value = zzz;
}
</script>
<input type="text" id="int" onchange="fn_do()">
You should use parseFloat, because DOM property value is a string, not number.
var zzz = parseFloat(numb).toFixed(2)
And don't use parseInt, because it'll give you an integer, for example parseInt("1.2") will be 1, then toFixed(2) gives you 1.00, while you actually want 1.20 I assume.
One more thing to care is, make sure input content is valid, for example parseFloat('qwer') will give you NaN. So the final code would look like:
var zzz = (parseFloat(numb) || 0).toFixed(2);
Instead of
var zzz = numb.toFixed(2)
Try
var zzz = parseFloat(numb).toFixed(2) //use parseInt() or parsFloat() as shown here.
Your complete will look like this :-
function fn_do() {
var numb = document.getElementById("int").value;
var zz = parseFloat(numb) || 0; //it will convert numb to float if conversion fails it will return 0.
var zzz = zz.toFixed(2);
document.getElementById("int").value = zzz;
}
Fiddle
var decimalForm = parseFloat(Math.round( intNum * 100) / 100).toFixed(2);
alert(decimalForm );
If I'm understanding this correctly, you want whatever number is put into the object with the id 'int' to be automatically converted to a decimal value with two placeholders. You could do something like this:
function convertToDecimal(value) {
var tempValue = Nath.Round(parseFloat(value) * 100);
var returnValue = tempValue * .01;
return returnValue;
}
That would ensure that you always get two decimal places
Exceptions: 1. if tempValue is a multiple of 10, only one decimal will come out
2. if tempValue is a multiple of 100, no decimals will be returned
Solution:
function convertDecimals(convertedValue) {
var tempValue = Nath.Round(parseFloat(value) * 100);
if ((tempValue % 10) == 0) {
if ((tempValue % 100) == 0) { var returnValue = convertedValue + .00; return returnValue; } else {
var returnValue = convertedValue + 0;
return returnValue;
}
}
return '';
}
So maybe the whole cde would look like this
function fn_do() {
var numb = document.getElementById("int").value;
//var numb = 123;
var zzz = convertToDecimal(numb);
zzz = zzz + convertDecimal(zzz);
document.getElementById("int").value = zzz;
}
function convertToDecimal(value) {
var tempValue = Nath.Round(parseFloat(value) * 100);
var returnValue = tempValue * .01;
return returnValue;
}
function convertDecimals(convertedValue) {
var tempValue = Nath.Round(parseFloat(value) * 100);
if ((tempValue % 10) == 0) {
if ((tempValue % 100) == 0) { var returnValue = convertedValue + .00; return returnValue; } else {
var returnValue = convertedValue + 0;
return returnValue;
}
}
return '';
}

Want to get specific value from string

I have a JavaScript string sentrptg2c#appqueue#sentrptg2c#vwemployees#.
I want to get last string vwemployees through RegExp or from any JavaScript function.
Please suggest a way to do this in JavaScript.
You can use the split function:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
str = str.split("#");
str = str[str.length-2];
alert(str);
// Output: vwemployees
The reason for -2 is because of the trailing #. If there was no trailing #, it would be -1.
Here's a JSFiddle.
var s = "...#value#";
var re = /#([^#]+)#^/;
var answer = re.match(s)[1] || null;
if you're sure the string will be separated by "#" then you can split on # and take the last entry... I'm stripping off the last #, if it's there, before splitting the string.
var initialString = "sentrptg2c#appqueue#sentrptg2c#vwemployees#"
var parts = initialString.replace(/\#$/,"").split("#"); //this produces an array
if(parts.length > 0){
var result = parts[parts.length-1];
}
Try something like this:
String.prototype.between = function(prefix, suffix) {
s = this;
var i = s.indexOf(prefix);
if (i >= 0) {
s = s.substring(i + prefix.length);
}
else {
return '';
}
if (suffix) {
i = s.indexOf(suffix);
if (i >= 0) {
s = s.substring(0, i);
}
else {
return '';
}
}
return s;
}
No magic numbers:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var ar = [];
ar = str.split('#');
ar.pop();
var o = ar.pop();
alert(o);
jsfiddle example

how to get formatted integer value in javascript

This is my integer value
12232445
and i need to get like this.
12,232,445
Using prototype how to get this?
var number = 12232445,
value = number.toString(),
parts = new Array;
while (value.length) {
parts.unshift(value.substr(-3));
value = value.substr(0, value.length - 3);
}
number = parts.join(',');
alert(number); // 12,232,445
It might not be the cleanest solution, but it'll do:
function addCommas(n)
{
var str = String(n);
var result = '';
for(var i = 0; i < str.length; i++)
{
if((i - str.length) % 3 == 0)
result += ',';
result += str[i];
}
return result;
}
Here is the function I use, to format thousands separators and takes into account decimals if any:
function thousands(s) {
var rx = /(-?\d+)(\d{3})/,
intDec = (''+s)
.replace(new RegExp('\\' + $b.localisation.thousandSeparator,'g'), '')
.split('\\' + $b.user.localisation.decimalFormat),
intPart = intDec[0],
decPart = intDec[1] || '';
while (rx.test(intPart)) {
intPart = intPart.replace(rx,'$1'+$b.localisation.thousandSeparator+'$2');
}
return intPart + (decPart && $b.localisation.decimalFormat) + decPart;
}
thousands(1234.56) //--> 1,234.56
$b.localisation is a global variable used for the session.
$b.localisation.thousands can have the values , or . or a space.
And $b.localisation.decimalFormat can have the values , or . depending on the locale of the user

Adding commas, decimal to number output javascript

I'm using the following code to count up from a starting number. What I need is to insert commas in the appropriate places (thousands) and put a decimal point in front of the last two digits.
function createCounter(elementId,start,end,totalTime,callback)
{
var jTarget=jQuery("#"+elementId);
var interval=totalTime/(end-start);
var intervalId;
var current=start;
var f=function(){
jTarget.text(current);
if(current==end)
{
clearInterval(intervalId);
if(callback)
{
callback();
}
}
++current;
}
intervalId=setInterval(f,interval);
f();
}
jQuery(document).ready(function(){
createCounter("counter",12714086+'',9999999999,10000000000000,function(){
alert("finished")
})
})
Executed here: http://jsfiddle.net/blackessej/TT8BH/3/
var s = 121221;
Use the function insertDecimalPoints(s.toFixed(2));
and you get 1,212.21
function insertDecimalPoints(s) {
var l = s.length;
var res = ""+s[0];
console.log(res);
for (var i=1;i<l-1;i++)
{
if ((l-i)%3==0)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res = res.replace(',.','.');
return res;
}
Check out this page for explanations on slice(), split(), and substring(), as well as other String Object functions.
var num = 3874923.12 + ''; //converts to a string
numArray = num.split('.'); //numArray[0] = 3874923 | numArray[1] = 12;
commaNumber = '';
i = numArray[0].length;
do
{
//we don't want to start slicing from a negative number. The following line sets sliceStart to 0 if i < 0. Otherwise, sliceStart = i
sliceStart = (i-3 >= 0) ? i-3 : 0;
//we're slicing from the right side of numArray[0] because i = the length of the numArray[0] string.
var setOf3 = numArray[0].slice(sliceStart, i);
commaNumber = setOf3 + ',' + commaNumber; //prepend the new setOf3 in front, along with that comma you want
i -= 3; //decrement i by 3 so that the next iteration of the loop slices the next set of 3 numbers
}
while(i >= 0)
//result at this point: 3,874,923,
//remove the trailing comma
commaNumber = commaNumber.substring(0,commaNumber.length-1);
//add the decimal to the end
commaNumber += '.' + numArray[1];
//voila!
This function can be used for if not working locale somite
number =1000.234;
number=insertDecimalPoints(number.toFixed(3));
function insertDecimalPoints(s) {
console.log(s);
var temaparray = s.split(".");
s = temaparray[0];
var l = s.length;
var res = ""//+s[0];
console.log(res);
for (var i=0;i<l-1;i++)
{
if ((l-i)%3==0 && l>3)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res =res +"."+temaparray[1];
return res;
}
function convertDollar(number) {
var num =parseFloat(number);
var n = num.toFixed(2);
var q =Math.floor(num);
var z=parseFloat((num).toFixed(2)).toLocaleString();
var p=(parseFloat(n)-parseFloat(q)).toFixed(2).toString().replace("0.", ".");
return z+p;
}

Categories