Cut from the third decimal without rounding - javascript

I know it's quite low quality of question but I get little bit confused now.
Here is the thing What I want to do.
100000 => 100.000
9997080000 => 9997080.000
I want to cut from the third decimal without rounding.
How can I do this? I used the toFixed() but all I want to do is just cut from third decimal. I think I'm complicated now.
It will be simple. Plz let me know. Thanks

From what I understand, this is what you want:
var number = "9002764000";
var result = number.slice(0, -3) +"."+ number.slice(-3);
console.log(result);
This will add a . after the last three digits i.e 9002764000 -> 9002764.000
https://jsfiddle.net/5yqhr7mo/
Hope it helps!

It sounds like you want a value for display. If so, you want to turn the number into a string (since numbers don't intrinsically have any particular number of digits to the right of the decimal). You can then easily insert the . before the last three digits using substring and substr:
function formatForDisplay(num) {
var str = String(num);
return str.substring(0, str.length - 3) + "." + str.substr(-3);
}
function test(num) {
console.log(num, "=>", formatForDisplay(num));
}
test(100000);
test(9997080000);

Alternatively, you could use String#replace and add a dot.
var number = 9002764000;
console.log(Math.floor(number).toString().replace(/(?=...$)/, '.'));

what about :
function formatNumber(num){
num=num/1000;
return num.toFixed(3);
}
console.log(formatNumber(9997080000));
console.log(formatNumber(100000000));
which will return what you expect if you work with integer

Math.floor() will round down essentially cutting off everything to the right of decimal point.

Related

(solved) Javascript : Cutting/Removing excess characters from a string if it exceeds the Limit

This question is a bit tricky to explain. Say i have an variable whose length is dynamic meaning it is random,i want to change its length to the first 5 or a certain amount of characters regardless of the length of the characters existing in the variable. I hope i could explain what i am trying to do
.________________________________________________________________________.
I really dont know which direction to go in or what step to take in order to reach my goal but i just copy/pasted some random code of the internet that didn't work so i did not think it is of any importance to include in this query,but i could share on demand
Pseudo code...
const str = "the string";
const start = 0;
// const end = str.length;
str.substring(start, (optional) end);
So if you want just first five characters, you do something like
str.substring(0, 5);
If it's only integers (numbers) you could simply generate a random whole number between 11111 and 99999 (so it's always 5 digits), like this:
let x = Math.floor((Math.random() * 99999) + 11111);
do you have a delimited amount of decimals? if not, you should remove Math.floor and convert into string and after that substring as in the other answer (and convert back into a Number if needed as Number). If yes, you should change the "11111" and "99999" to the length of integers needed, and use toFixed() to limit the number of decimals. –
DavidTaubmann

Remove numbers after decimal in javascript

var randomNumber = (Math.random()*3 + 3.5); randomNumber;
alert(randomNumber)
This piece of code returns a number like
4.589729345235789
I need it to return
4.5
So need it to remove all the numbers after the decimal except the first one, can anyone show me how to do that?
You use Number.prototype.toPrecision() with parameter 2, Number.prototype.toFixed() with parameter 1.
+randomNumber.toPrecision(2);
Alternatively, you can use String.prototype.slice() with parameters 0, 3
+String(randomNumber).slice(0, 3);
If you need to set the amount of decimal places in a number, you can use toFixed(X), where X is the amount of decimal places you want to have.
For example,
4.589729345235789.toFixed(1); would result in 4.6.
Keep in mind, this will convert the number into a string.
If you need absolute accuracy and 4.6 is not good enough for you, see this Stackoverflow post, which has this as a more "accurate" method for your case:
var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
Notice the {0,2} inside of that, which is the range. You can change it to {0,1} in your case.

whole number in javascript?

I get 28.6813276578 when i multiply 2 numbers a and b, how can i make it whole number with less digits
and also, when i multiply again i get results after first reult like 28.681321405.4428.68 how to get only one result ?
<script>
$(document).ready(function(){
$("#total").hide();
$("#form1").submit(function(){
var a = parseFloat($("#user_price").val());
var b = parseFloat($("#selling").val());
var total = a*b;
$("#total").append(total)
.show('slow')
.css({"background":"yellow","font-size":50})
;
return false;
});
});
</script>
You can do several things:
total = total.toFixed([number of decimals]);
total = Math.round(total);
total = parseInt(total);
toFixed() will round your number to the number of decimals indicated.
Math.round() will round numbers to the nearest integer.
parseInt() will take a string and attempt to parse an integer from it without rounding. parseInt() is a little trickier though, in that it will parse the first characters in a string that are numbers until they are not, meaning parseInt('123g32ksj') will return 123, whereas parseInt('sdjgg123') will return NaN.
For the sake of completeness, parseInt() accepts a second parameter which can be used to express the base you're trying to extract with, meaning that, for instance,
parseInt('A', 16) === 10 if you were trying to parse a hexidecimal.
See Math.round(...).
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/round
In addition to the other answers about rounding, you are appending the answer to "total" by using
$("#total").append(total)
You need to replace the previous text rather than appending by using
$("#total").html(total)

strip decimal points from variable

I have a series of variables that have a decimal point and a few zeros. How do I strip the variable so it goes from 1.000 to 1?
Simply...
Math.round(quantity);
...assuming you want to round 1.7 to 2. If not, use Math.floor for 1.7 to 1.
use parseInt();
parseInt("1.25");//returns 1
parseInt("1.85");//returns 1
parseInt(1.25);//returns 1
parseInt(1.85);//returns 1
Use number = ~~number
This is the fastest substitute to Math.floor()
parseInt is the slowest method
math.floor is the 2nd slowest method
faster methods not listed here are:
var myInt = 1.85 | 0;
myInt = 1;
var myInt = 1.85 >> 0;
myInt = 1;
Speed tests done here:
http://jsperf.com/math-floor-vs-math-round-vs-parseint/2
Use Math.trunc(). It does exactly what you ask. It strips the decimal.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
For rounding numbers to the nearest Integer you can use Math.round() like so:
Math.round("1.000"); // Will produce 1
Math.round(123.4234); // Will produce 123
You don't need jQuery for this.
You can use parseInt just fine. From the page:
document.write(parseInt("10.33") + "<br />"); // 10
Here's another nice example:
I often use Math.round and toLocateString to convert numbers containing decimal places, into a more readable string, with thousand separators:
var myNumberAsString = "1234567.890123" // "1234567.890123"
var myNumber = Math.round(0.0 + myNumberAsString); // 1234568
return myNumber.toLocaleString(); // "1,234,568"
I find this useful when loading decimal values from, say a JSON Web Service, and need to display them in a friendlier format on a web page (when, of course, I don't need to display all of the decimal places).
A faster, more efficient way would be to use JavaScript's bitwise operators, like so:
function stripDecimals(n) {
return n | 0;
}
// examples:
stripDecimals(23.245); // => 23
stripDecimals(100.015020); // => 100
The | (OR operator) will treat the numbers as 32-bit (binary 0s and 1s), followed by returning the desired result depending on the operands, which in this case would result to an integer stripped of all decimal places.
I suggest you use something called Math.trunc()... put your number in the parentheses. The reason I don't suggest you use Math.round() is that it might change the integer part of your decimal number which some people won't want though you can use Math.round() if you know you want to get the closest integer.

Perform a replace on a integer?

I promise that I've done my homework on this. It's a basic question, but I'm not terribly familiar with Jquery. Assume the following...
var cac = parseInt($("#currentAccess").val());
var acn = parseInt($("#addCapital").val());
var tn = (cac + acn);
How do I then take the variable tn, do a replace on it, and output it? This is an example that doesn't work...
$("#totalNeedG").append("<p>$" + tn.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + "</p>");
Thanks for this simple help!
.replace() is a String method. Not a Number method.
Convert it to a String.
var tn = ((cac + acn) + '');
String(yourNumber) returns a string containing your number.
To convert it back, use parseInt(yourString, 10).
And, as you are not doing it, ALWAYS use the second argument if parseInt(str, base)! If you don't, the base is determined automatically which is almost never what you want:
parseInt('010') == 8 // 0-prefix means octal
parseInt('0xff') == 255 // 0x-prefix means hex
While it's unlikely that somebody puts a number starting with 0x in a field chances are high someone puts a leading zero for some reason.

Categories