This question already has an answer here:
Format a javascript number with a Metric Prefix like 1.5K, 1M, 1G, etc [duplicate]
(1 answer)
Closed 7 years ago.
To start with you need...
function m(n,d){x=(''+n).length,p=Math.pow,d=p(10,d)
x-=x%3
return Math.round(n*d/p(10,x))/d+" kMGTPE"[x/3]}
Then calling like so...
// m( ANY NUMBER HERE or VAR LIKE I USE,HOW DECIMAL PLACES)
m(110000,2)
However instead of the above's result of 0.11M, I would like it to display 110k.
What you have there is an example of an overly optimized script, lets make it more developer friendly an readable
function metricPrefix(rawNumber,decimalPlaces){
var sufixes= " kMFGPE";
var numberLength =(''+n).length;
decimalPlaces=Math.pow(10,d); //raise 10 to the number of decimal places
var modLen = numberLength - numberLength%3;
var sufix = sufixes[modLen/3];
return Math.round(rawNumber*decimalPlaces/decimalPlaces(10,modLen))/decimalPlaces+ sufix;
}
Now it's easier to work with. We can see the issue is that we need to adjust for when the string is divisible by 3, so lets fix that.
function metricPrefix(rawNumber,decimalPlaces){
var sufixes= " kMFGPE";
var numberLength =(''+rawNumber).length;
decimalPlaces=Math.pow(10,decimalPlaces); //raise 10 to the number of decimal places
//THis is the change
//If the length is divisable by 3 take 3 off the length
var modLen = numberLength%3 == 0 ? numberLength - 3 - (numberLength%3) : numberLength - (numberLength%3);
console.log(modLen);
var sufix = sufixes[(modLen/3)]
console.log(sufix)
return Math.round(rawNumber*decimalPlaces/Math.pow(10,modLen))/decimalPlaces+ sufix;
}
$(document).ready(function(){
$("#result").html(metricPrefix(110000,2));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>
Related
This question already has answers here:
How can I remove the decimal part from JavaScript number?
(16 answers)
Closed 2 months ago.
How can i make the result of the calculation to display no decimals - for all the results ?
now the number is variable on a slider that gives a number from : 5000 - 100000
and is then divided or multiplied with : X
the problem if X is somthing like : * 0.0001097 the number i is a mile long
i just want the result to be wihtout decimals
i am a real amateur in this field.. have mercy with me hahah
function do_on_range_change_pages() {
$('.betrag').text(pages);
$('.name1').text((pages * 0.001));
$('.name2').text((pages * 0.03));
$('.name3').text((pages / 22));
}
*how can i make the result of this display no decimals ?*
$('.name3').text((pages / 22 **?????**));
In Javascript, you could remove decimals with severals solutions !
The parseInt() function is the slower (!).
let myNumber = 5.0214;
let myOtherNumber = 5.9;
// With Math.floor() method
let myNymberWithoutDecimals = Math.floor(myNumber) // 5
let myOtherWithoutDecimals = Math.floor(myOtherNumber) // 5
// With Math.round() method
let myNymberWithoutDecimals = Math.round(myNumber) // 5
let myOtherWithoutDecimals = Math.round(myOtherNumber) // 6
// with parseInt()
let myNymberWithoutDecimals = parseInt(myNumber) // 5
let myOtherWithoutDecimals = parseInt(myOtherNumber) // 5
// with toFixed(number)
myNumber.toFixed(2) // 5.02
myNumber.toFixed(1) // 5.0
myNumber.toFixed() // 5
With your example :
function do_on_range_change_pages() {
$('.betrag').text(pages);
$('.name1').text((pages * 0.001).toFixed());
$('.name2').text((pages * 0.03).toFixed());
$('.name3').text((pages / 22).toFixed());
}
Better advice : new to JS ? Try to use google.
My research : https://www.jsdiaries.com/how-to-remove-decimal-places-in-javascript/
Try https://beta.sayhello.so/, this search engine could find snippets :) !
Have a nice day :)
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 1 year ago.
Does anyone know why the exponent and round up functions aren't giving me the correct answers? I've gone through a load of debugging and I can't figure out what I'm doing that's making it's value abnormally large (like 25 orders larger)
function CAPEX(){
var initial = document.getElementById("CAPEX").value;
var lifespan = document.getElementById("life").value;
var interest = document.getElementById("IR").value;
var capitalrepayment = initial/lifespan;
var i;
var cap=0;
var expense =0;
for (i=0; i<lifespan;i++){
expense = capitalrepayment + (initial*interest);
cap = cap + expense;
initial = initial - capitalrepayment;
}
denominator = Math.pow((1+interest), lifespan);
console.log(denominator);
return cap;
}
I have a similar sort of issue here too where Math.ceil is returning a completely different answer too.
if(selected_scenario == "Divers"){
var totalTechnicians = numberNeeded * 3;
var supervisors = totalTechnicians/3;
var othertechnicians = totalTechnicians-supervisors;
var boats= Math.ceil((totalTechnicians+numberNeeded)/12);
divertotal = (numberNeeded*580)+(supervisors*516)+(othertechnicians*276)+(boats*2345)+9230+(boats*20);
}
For reference interest is 0.02, lifespan is 25, numberNeeded is 23. I'm reading these values in directly from a form number input.
The denominator should be 1.64 and boats should be 8.
The values that you are getting from the DOM are strings. You need to convert them to numbers before you can apply any mathematical operations to them. Try using parseInt() or parseFloat()
This question already has answers here:
Formatting a number with exactly two decimals in JavaScript
(32 answers)
Closed 5 years ago.
When I am trying to calculate the values
My output has 15 digits in decimal values
Like if x=3
Then in output it is showing
5.196152422706632
But how can I limit it to
5.19615
How to limit decimal digits in output from 15 digits to 5 digits in JavaScript?
Here is my script:
<script>
function myFunction() {
var x = document.getElementById("phase").value;
document.getElementById("demo").innerHTML = "<b>V<sub>L</sub>is</b><br>" + Math.sqrt(3)*x + "volts";
}
</script>
How can I use this:
double number = 0.#############;
DecimalFormat numberFormat = new DecimalFormat("#.#####");
The toFixed method allows you to set the number of digits.
I would use it like this:
document.getElementById("demo").innerHTML = "<b>V<sub>L</sub>is</b><br>" + (Math.sqrt(3) * x).toFixed(5) + "volts";
Btw, java is a completely different language to javascript - you're not using it here
In javascript you can fix the no of digits you want to display after decimal by using the function - toFixed(n).
Here n specifies the no of digits to display after decimal.
<script>
function myFunction() {
var x = document.getElementById("phase").value;
document.getElementById("demo").innerHTML = "<b>V<sub>L</sub>is</b><br>" + (Math.sqrt(3)*x).toFixed(5) + "volts";
}
</script>
In java you can do it like this.
public static void main(String[] args)
{
String value = String.format("%.3f", Math.sqrt(3)*9);
System.out.println("Value with 3 decimals: " + value);
}
In javascript you should check this anwser.
This question already has answers here:
String Conversion in Javascript (Decimal to Binary)
(5 answers)
Closed 7 years ago.
I would like to ask help whether am I doing the right thing or not. You see I am trying to test myself by displaying the bit pattern of a number in the most efficient way as possible. But I'm having trouble on how to display the pattern cause I'm still learning javascript. Here's my code.
<script>
var bitPattern = function(given) {
for(var i = 1 << 31; i > 0; i = i / 2){
document.write((given & i) ? 1 : 0);
}
};
var number = prompt("Enter a number to convert: ");
bitPattern(number);
</script>
The best way to do this is:
var number = prompt("Enter a number to convert: ");
var bitPattern = parseInt(number).toString(2);
document.write(bitPattern);
This question already has answers here:
How do I check that a number is float or integer?
(52 answers)
Closed 7 years ago.
im trying to check if a number is a whole after a calculation. What I have so far prints out how many times one number gets divided by another, but when the number is not whole it dose not print anything out. Heres my code:
function round() {
var percent = document.getElementById('percent_sale').value;
var perShare = document.getElementById('singleShare').value;
var result = (percent / perShare);
if(result % 1 == 0) {
document.getElementById('results1').innerHTML = ('Number of shares:'+result);
} else {
document.getElementById(results1).innerHTML = ('number of shares must ');
}
}
The values get input buy a user, and the percent for sale is say 50 and the single share is say 2.5 this would return 20 shares.
What I need is if I put in something like 50 for sale and 3.15 single share it tells the user to make equal number of shares as it would return 15.87
Any ideas where ive gone wrong?
Convert your number into string and then check if the string contains only numbers
var num = 15;
var n = num.toString();
This will convert it into string then this
String.prototype.isNumber = function(){return /^\d+$/.test(this);}
console.log("123123".isNumber()); // outputs true
console.log("+12".isNumber()); // outputs false
For further reference.Link StackOverFlow