How can I add percent to a sum? I have tried var sum = 3.25 + '3.4%'; but it didn't work. I'm just getting 0.00 as an answer.
To "add a percent to a number" means "multiply the number by (1 + pct)":
var sum = 3.25;
sum = sum * (1 + 0.034);
You could equivalently skip the 1 (that's just the way I think about it) and add:
var sum = 3.25;
sum += sum * 0.034;
So if you're starting off with a string representation of a percentage, you can use parseFloat() to make it a number:
var pct = "3.4%"; // or from an <input> field or whatever
pct = parseFloat(pct) / 100;
The parseFloat() function conveniently ignores trailing non-numeric stuff like the "%" sign. Usually that's kind-of a problem, but in this case it saves the step of sanitizing the string.
The simplest method is to use arithmetic operators.
var sum = 3.25
sum += sum *= 0.034;
< 3.3605
String concatenation and number adding using the same + symbol. You need to use () around the numbers.
var sum = (3.25+3.4)+"%";
let's assume that you want to add x percent to the current number :
const percentage = 14.5; let number = 100 const numberPlusPercentage = number + number / 100 * percentage
console.log('result = 'numberPlusPercentage.toFixed(2))
result = 114.5
Related
This question already has answers here:
Truncate (not round off) decimal numbers in javascript
(32 answers)
Closed 1 year ago.
I would like to format my numbers to always display 2 decimal places. lets say: I have a number => 21.268998 , the o/p I'm looking is to chop the rest of the decimal point and keep only the first 2 i.e:
21.26
however with the tofixed or toPrecision approach to always rounds to a certain decimal which is causing issues when a number is 99.999999, it rounds to 100.000 which is not right.
var num1 = "1";
document.getElementById('num1').innerHTML = (Math.round(num1 * 100) / 100).toFixed(2); // this is showing correctly
var num2 = "99.99999";
document.getElementById('num2').innerHTML = (Math.round(num2 * 100) / 100).toFixed(2);// this is incorrect=> I want to show 99.99
any idea how to get the first numbers to show always without rounding them off to the next number.
Jsfiidle:
https://jsfiddle.net/8ohvyczg/1/
You can use slice method in javascript:
var num2 = 99.99999;
num2 = num2.slice(0, (num2.indexOf("."))+3);
document.getElementById('num2').innerHTML = num2;
Did u tried Math.trunc()?
var num = "99.99999";
var round=(Math.round(num * 100) / 100).toFixed(2)
var trunc=(Math.trunc(num * 100) / 100)
console.log(round);
console.log(trunc);
Here's an approach of a simple truncate, and not round off:
var number = 26.4363
var str = number.toString();
console.log(str.substring(0, str.indexOf(".")+3));
Many ways to do that. But you can write a custom function to do that. I use split and substring.
const num = "99.91999";
function parseNumber(num)
{
arr = num.split('.');
return arr[0] + '.' + arr[1].substring(0,2);
}
console.log(parseNumber(num))
Was using ExtJS for formatting numbers to percentage earlier. Now as we are not using ExtJS anymore same has to be accomplished using normal JavaScript.
Need a method that will take number and format (usually in %) and convert that number to that format.
0 -> 0.00% = 0.00%
25 -> 0.00% = 25.00%
50 -> 0.00% = 50.00%
150 -> 0.00% = 150.00%
You can use Number.toLocaleString():
var num=25;
var s = Number(num/100).toLocaleString(undefined,{style: 'percent', minimumFractionDigits:2});
console.log(s);
No '%' sign needed, output is:
25.00%
See documentation for toLocaleString() for more options for the format object parameter.
Here is what you need.
var x=150;
console.log(parseFloat(x).toFixed(2)+"%");
x=0;
console.log(parseFloat(x).toFixed(2)+"%");
x=10
console.log(parseFloat(x).toFixed(2)+"%");
Modern JS:
For any of these, remove * 100 if you start with a whole number instead of decimal.
Basic
const displayPercent = (percent) => `${(percent * 100).toFixed(2)}%`;
Dynamic with safe handling for undefined values
const displayPercent = (percent, fallback, digits = 2) =>
(percent === null || percent === undefined) ? fallback : `${(percent * 100).toFixed(digits)}%`;
Typescript:
const displayPercent = (percent: number) => `${(percent * 100).toFixed(2)}%`;
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction(num) {
number = num.toString();;
console.log(number)
var words2 = number.split(".");
for (var i = 0; i < words2.length; i++) {
words2[i] += " ";
}
num1 = words2[0];
num2 = words2[1];
num1 = num1.trim();
if(num2==undefined){
number1 = num1+'.00%';
return number1;
}else{
num2 = num2.trim();
number1 = num1+'.'+num2+'%';
return number1;
}
}
document.getElementById("demo").innerHTML = myFunction(50.12);
</script>
</body>
</html>
I had decimal values such as 0.01235 and 0.016858542 that I wanted to convert to percentages 1.235% and 1.6858542% respectively. I thought it was going to be easy, just calculate (0.012858542 * 100) and I'm good to go. I was wrong, (0.012858542 * 100) = 1.2858542000000002 because of decimal conversion.
Let's add toFixed() to the calculation and I end up with the right value.
(0.012858542*100).toFixed(7) // returns "1.2858542"
(0.01235*100).toFixed(7) // returns "1.2350000"
I don't like to show four trailing zeros when they're unnecessary. One solution I thought about was to use replace() to remove all trailing zeros but I ended up using Numeral.js instead because it does all the work for me while it's lightweight. I can recommend it!
import numeral from 'numeral';
numeral(0.012858542 * 100).format('0.00[0000]') // returns "1.2858542"
numeral(0.01235 * 100).format('0.00[0000]') // returns "1.235"
Transform number to percentage with X float decimal positions
function toPercent(number, float) {
var percent = parseFloat(number * 100).toFixed(float) + "%";
return percent;
}
Ok, I'm not a coder, I've no school about it but ... I can't figure out why this little operation returns a NaN value!
I've this var at the beginning
// Varialbes for simulation purpose
var Simulation = false;
var FakeCapital = 0;
var PercentOfTotal = 100;
// Variables
var Capital = (engine.getBalance() / 100).toFixed(2);
var UsableBalance = Math.floor(PercentOfTotal / 100 * Capital);
var StartingBalance = UsableBalance;
if (FakeCapital > 0 && Simulation) {
Capital = FakeCapital;
UsableBalance = Math.floor(PercentOfTotal / 100 * Capital);
StartingBalance = UsableBalance;
}
So If I activate the similation var and if I want to use another capital, the script use the fakecapital to test my script.
Here all works but I think that here there's the problem, specially the UsableBalance = Math.floor(PercentOfTotal / 100 * Capital);
Because when the script run:
If I don't use the simulation, all goes right
If I use the simulation and the fake capital, all goes right
But if I use the simulation and I want to use the real capital, the UsableBalance var is strange, not immediately but when the script runs! I try to explain better
Let's assume that I use the simulation phase and I want to use the real capital
Your ballance is: 87.26 bits.
I'll use: 87 bits for this session, as your request.
Here all ok, but this code:
if (TemporaryLoss <= 0) {
Capital += LastProfit;
UsableBalance = Math.floor((PercentOfTotal / 100) * Capital);
TemporaryLoss = 0;
}
Return this:
TemporaryLoss: 0
Capital: 87.26
LastProfit: 1.0299999999999998
PercentOfTotal: 100
Capital: 87.261.0299999999999998
Why the math return this strange number? like a concatenation of 2 numbers? Seems that the script use the var like a text and not like a numbers.
Any Idea?
You make a string with toFixed()
var Capital = (engine.getBalance() / 100).toFixed(2);
and used it later as number, but it is a string.
Capital += LastProfit;
Solution: If fixed is necessary, then use parseFloat() to make a number again.
Lets take an example :
var x = 1;
var y = '1';
var z = x + (y*10)
the datatype of variable y is implicitly coerced to number for the current operation, to evaluate the value of z.
So, for z , y is taken as a number because (y*10) caused implicit coercion, but doesn't change y itself to number
In your case ,
var Capital = (engine.getBalance() / 100).toFixed(2);
causes Capital to become a string.
Hence any further addition operations with Capital result in concatenation
You will have to explicitly convert to int or float as mentioned earlier.
I have scoured the internet and I haven't found a solution that really works for me, yet.
var tv = Length * Type;
if (tv < 0)
{
cForm.voltage.value = "-" + Math.abs(tv) + " V";
}
else...
Some of the calculations with these two numbers come out to about the 15th decimal for some reason. I would like to limit the decimal amount that is returned, and NOT allow the number to round up or down. On a calculator it only comes out to about the third decimal, but Math.abs() brings it too far out.
.toFixed() Doesn't work for me because if the number only has 2 decimals it will add additional zeros at the end. I only want to display up to the fourth if it is calculated.
Just expanding on #goto-0 s comment, with the correct # of decimal places.
var tv = Length * Type;
if (tv < 0)
{
cForm.voltage.value = "-" + (Math.round(Math.abs(tv) * 10000) / 10000) + " V";
}
else...
Here's the implementation as a function that truncates the extra decimal places. If you want to round the output you could just use Number.toPrecision().
function toFixedDecimals(num, maxDecimals) {
var multiplier = Math.pow(10, maxDecimals);
return Math.floor(num * multiplier) / multiplier
}
console.log(toFixedDecimals(0.123456789, 4));
console.log(toFixedDecimals(100, 4));
console.log(toFixedDecimals(100.12, 4));
I'm sure its not the most efficient approach but it is pretty brainless -
grab your result
split it into an array based on the decimal point
then trim the decimal part to two digits (or however many you would like).
concat the pieces back together
Sorry for the long variable names - just trying to make it clear what was happening : )
// your starting number - can be whatever you'd like
var number = 145.3928523;
// convert number to string
var number_in_string_form = String(number);
// split the number in an array based on the decimal point
var result = number_in_string_form.split(".");
// this is just to show you what values you end up where in the array
var digit = result[0];
var decimal = result[1];
// trim the decimal lenght to whatever you would like
// starting at the index 0 , take the next 2 characters
decimal = decimal.substr(0, 2);
// concat the digit with the decimal - dont forget the decimal point!
var finished_value = Number(digit + "." + decimal);
In this case the finished_value would = 145.39
This question already has answers here:
Truncate (not round off) decimal numbers in javascript
(32 answers)
Closed 8 years ago.
Im trying to get a number with precision to 2 decimals, for example this is what I want, if I have the numbers:
3.456 it must returns me 3.45
3.467 = 3.46
3.435 = 3.43
3.422 = 3.42
I don't want to round up or down or whatever just to get the numbers I see 2 places after .
Thanks
Okay, here is the answer
var a = 5.469923;
var truncated = Math.floor(a * 100) / 100; // = 5.46
Thanks everyone for helping.
Assuming Positive Numbers:
The code:
function roundDown(num,dec) {
return Math.floor(num*Math.pow(10,dec))/Math.pow(10,dec);
}
The test:
function test(num, expected) {
var val = roundDown(num,2);
var pass = val === expected;
var result = pass ? "PASS" : "FAIL";
var color = pass ? "GREEN" : "RED";
console.log("%c" + result + " : " + num + " : " + val, "background-color:" + color);
}
test(3.456, 3.45);
test(3.467, 3.46);
test(3.435, 3.43);
test(3.422, 3.42);
Basic idea:
Take number
Multiply the number to move decimal place to number of significant figures you want
Floor the number to remove the trailing numbers
Divide number back to get the correct value
If you want to have a trailing zero, you need to use toFixed(2) which will turn the number to a string.
function roundDown(num,dec) {
return Math.floor(num*Math.pow(10,dec))/Math.pow(10,dec).toFixed(2);
}
and the test cases would need to change to
test(3.456, "3.45");
test(3.467, "3.46");
test(3.435, "3.43");
test(3.422, "3.42");
Another option is a regular expression.
function roundDown(num,dec) {
var x = num.toString().match(/(\d*(\.\d{2}))?/);
return x ? parseFloat(x[0]) : "";
//return x ? parseFloat(x[0]).toFixed(2) : "";
}
Use String operation to achieve it.
var n = 4.56789;
var numbers = n.toString().split('.');
result = Number(numbers[0]+"."+numbers[1].substr(0,2));
alert(result);
Fiddle
You are looking at the number as if it were a string of digits, rather than a single value, so treat it like a string.-
function cutoff(n, cut){
var parts= String(n).split('.'), dec= parts[1];
if(!cut) return parts[0];
if(dec && dec.length>cut) parts[1]= dec.substring(0, cut);
return parts.join('.');
}
var n= 36.938;
cutoff(n,2)
/* returned value: (String)
36.93
*/
If you want a number, +cutoff(n,2) will do.
function truncateDec(num, decplaces) {
return (num*Math.pow(10,decplaces) - num*Math.pow(10,decplaces) % 1)/Math.pow(10,decplaces);
}
alert(truncateDec(105.678, 2)); // Returns 105.67
alert(truncateDec(105.678, 1)); // Returns 105.6
This could be simplified further if you do not require a dynamic number of decimal places
function truncateDec(num) {
return (num*100 - num*100 % 1)/100;
}
alert(truncateDec(105.678)); // Returns 105.67
How does it work?
The concept is that the main truncation works by getting the remainder from dividing the original decimal by 1. The remainder will be whatever is in the decimals places. The remainder operator is %
105.678 % 1 = 0.678
By subtracting this remainder from the original number, we will be left with only the integer.
105.678 - 0.678 = 105
To include x number of decimal places, we need to first multiply the original number by 10 to the power of that number of decimal places, thereby shifting the decimal backward by x positions. In this example, we will take x = 2.
105.678 * 10^2
= 105.678 * 100
= 10567.8
Now, we repeat the same procedure by subtracting the remainder again.
10567.8 % 1 = 0.8
10567.8 - 0.8 = 10567
And to return back to the number of places as requested, we divide it back by 10^x
10567 / 10^2
= 10567 / 100
= 105.67
Hope it helps!