How as a round number? - javascript

I need a round to two number after comma.
example
5000.0000 to 5000
5000.123 to 5000.12
5000.136 to 5000.13
how do this?
I need function x.toFixed(2); but if at the end of two zero, then they should not show

You can use this javascript function to round the number
function roundNumber(rnum, rlength) {
var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
return parseFloat(newnumber);
}
var num = roundNumber(5000.0000,0); //will return 5000

As #freakish suggests, toFixed is good idea to round numbers. If you want to floor it, I suggest
parseInt(5000.136*100)/100;

Since x.toFixed(2) returns a string you may do something like this:
function cut(str) {
if (str[str.length-1] == "0")
return str.substr(0, str.length-1);
if (str[str.length-1] == ".")
return str.substr(0, str.length-1);
return str;
}
x = cut(cut(cut(x.toFixed(2))));
Not the most elegant (for example you could add the function to string's prototype), but definetly working.

This link can help you
http://www.w3schools.com/jsref/jsref_tofixed.asp
Example
Convert a number into a string, keeping only two decimals:
var num = 5.56789; var n=num.toFixed(2);
The result of n will be:
5.57

Related

Sum Strings as Numbers

I am trying to solve a kata that seems to be simple on codewars but i seem to not be getting it right.
The instruction for this is as simple as below
Given the string representations of two integers, return the string representation of the sum of those integers.
For example:
sumStrings('1','2') // => '3'
A string representation of an integer will contain no characters besides the ten numerals "0" to "9".
And this is what i have tried
function sumStrings(a,b) {
return ((+a) + (+b)).toString();
}
But the results solves all except two and these are the errors i get
sumStrings('712569312664357328695151392', '8100824045303269669937') - Expected: '712577413488402631964821329', instead got: '7.125774134884027e+26'
sumStrings('50095301248058391139327916261', '81055900096023504197206408605') - Expected: '131151201344081895336534324866', instead got: '1.3115120134408189e+29'
I don't seem to understand where the issues is from. Any help would help thanks.
The value you entered is bigger than the int type max value. You can try changing your code to:
function sumStrings(a,b) {
return ((BigInt(a)) + BigInt(b)).toString();
}
This way it should return the right value
You could pop the digits and collect with a carry over for the next digit.
function add(a, b) {
var aa = Array.from(a, Number),
bb = Array.from(b, Number),
result = [],
carry = 0,
i = Math.max(a.length, b.length);
while (i--) {
carry += (aa.pop() || 0) + (bb.pop() || 0);
result.unshift(carry % 10);
carry = Math.floor(carry / 10);
}
while (carry) {
result.unshift(carry % 10);
carry = Math.floor(carry / 10);
}
return result.join('');
}
console.log(add('712569312664357328695151392', '8100824045303269669937'));
console.log(add('50095301248058391139327916261', '81055900096023504197206408605'));
The problem is that regular javascript integers are not having enough space to store that much big number, So it uses the exponential notation to not lose its precision
what you can do is split each number into parts and add them separately,
one such example is here SO answer
My solution is:
function sumStrings(a,b) {
return BigInt(a) + BigInt(b) + ''
}
Converting from a string to a number or vice versa is not perfect in any language, they will be off by some digits. This doesn't seem to affect small numbers, but it affects big numbers a lot.
The function could go like this.
function sumStrings(a, b) {
return (BigInt(a) + BigInt(b)).toString() // or parseInt for both
}
However, it's still not perfect since if we try to do:
console.log((4213213124214211215421314213.0 + 124214321214213434213124211.0) === sumStrings('4213213124214211215421314213', '124214321214213434213124211'))
The output would be false.

Evaluating numbers that include thousand separators

I understand that if the parseFloat function encounters any character other than numeric characters (0-9+-. and exponents) it just evaluates the number up to that character, discarding anything else.
I'm having a problem where I need to be able to validate numbers with thousand separators like so:
var number = "10,000.01"; //passes
var numberWithoutThousand = "10000.01"; //fails
//i.e:
if(parseFloat(number) <= 10000) {
return true;
}
//passess
problem is the above code returns true when technically that number is larger than 10,000.
What's the best way to get around this? I've considered stripping out the comma before testing the number, but not sure that is a good strategy.
You don't have numbers, you have strings, so just removing the comma is the way to go
number = number.replace(/\,/g, '');
Your "stripping the comma" strategy seems good to me.
if ( parseFloat( number.replace(",","") ) ) { etc(); }
As has been suggested, to have , in the number it must be a string and so do a search and replace. If you are having to do this on a regular basis then make yourself a reusable function.
Javascript
function myParseFloat(value) {
if (typeof value === 'string') {
value = value.replace(/,/g, '');
}
return parseFloat(value);
}
var number1 = "10,000.01",
number2 = "10000.01",
number3 = 10000.01;
console.log(myParseFloat(number1), myParseFloat(number2), myParseFloat(number3));
Output
10000.01 10000.01 10000.01
On jsFiddle

Show numbers to second nearest decimal

I'm very new to Javascript so please bear with me.
I have this function that adds up a total. How do I make it so that it shows the nearest two decimal places instead of no decimal places?
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".row-total-input").each(function() {
var valString = $(this).val() || 0;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(CommaFormatted(prodSubTotal));
}
Thank you!
Edit: As requested: commaFormatted:
function CommaFormatted(amount) {
var delimiter = ",";
var i = parseInt(amount);
if(isNaN(i)) { return ''; }
i = Math.abs(i);
var minus = '';
if (i < 0) { minus = '-'; }
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if (n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
amount = "$" + minus + n;
return amount;
}
Well parseInt parses integers, so you are getting rid of any decimals right there. Use parseFloat.
E.g.
parseFloat('10.599').toFixed(2); //10.60
You might also want to change your commaFormatted function to something like:
function commaFormatted(amount) {
if (!isFinite(amount) || typeof amount !== 'number') return '';
return '$' + amount.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
}
commaFormatted(0); //$0.00
commaFormatted(1.59); //$1.59
commaFormatted(999999999.99); //$999,999,999.99
Use to function toFixed(2)
The 2 is an integer parameter that says use 2 decimal points, assuming your comma formatted code does not turn it into a string. (If it does, fix the decimals BEFORE you run it through the formatting)
$("#product-subtotal").val(CommaFormatted(parseFloat(prodSubTotal).toFixed(2)));
Remember to parseFloat because the val() could be a string!`
You're looking for toFixed(). It takes one parameter, digits. The parameter is documented as follows:
The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0.
Do also note that parseInt() parses integers, truncating any decimals you might have. parseFloat() will preserve decimals as expected.
I solved my problem. I simply changed:
$("#product-subtotal").val(CommaFormatted(prodSubTotal));
to
$("#product-subtotal").val(prodSubTotal);
As I stated in the comments, this was not a script I wrote. It is a script Chris Coyier wrote and I was just trying to amend it. I guess I didn't need to use CommaFormatted for my purposes?
Thank you all for your help!

check if number string contains decimal?

After doing a sqrt()
How can I be check to see if the result contains only whole numbers or not?
I was thinking Regex to check for a decimal - if it contains a decimal, that means it didn't root evenly into whole numbers. Which would be enough info for me.
but this code isnt working...
result = sqrt(stringContainingANumber);
decimal = new RegExp(".");
document.write(decimal.test(result));
I bet there's other ways to accomplish the same thing though.
. means any char.
You have to quote the dot. "\."
Or you could test
if (result > Math.floor(result)) {
// not an decimal
}
You can use the % operator:
result % 1 === 0; // rest after dividing by 1 should be 0 for whole numbers
Use indexOf():
​var myStr = "1.0";
myStr.indexOf("."); // Returns 1
// Other examples
myStr.indexOf("1"); // Returns 0 (meaning that "1" may be found at index 0)
myStr.indexOf("2"); // Returns -1 (meaning can't be found)
"." has meaning in the regex syntax which is "anything" you need to escape it using "\."
If its a string we can just use split function and then check the length of the array returned. If its more than 1 it has decimal point else not :). This doesn't work for numbers though :(. Please see the last edit. It works for string as well now :)
function checkDecimal() {
var str = "202.0";
var res = str.split(".");
alert(res.length >1);
var str1 = "20";
alert(str1.split(".").length>1);
}
Hope it helps someone.
Happy Learning :)
Are you looking for checking string containing decimal digits ,
you can try like this
var num = "123.677";
if (!isNaN(Number(num)) {
alert("decimal no");
}
else {
alert("Not a decimal number");
}
I am sorry. This answer is too late. but I hope this will help.
function isThisDecimal(val){
if (!(val.indexOf(".") == -1)){
return true; // decimal
}
return false; // number
}
console.log(isThisDecimal("12.00")); //true
console.log(isThisDecimal("12.12")); //true
console.log(isThisDecimal("12"));// false

Get first two digits of a string, support for negative 'numbers'

I have the following strings in JavaScript as examples:
-77.230202
39.90234
-1.2352
I want to ge the first two digits, before the decimal. While maintaining the negative value. So the first one would be '-77' and the last would be '-1'
Any help would be awesome!
Thank you.
You can simply use parseInt().
var num = parseInt('-77.230202', 10);
alert(num);
See it in action - http://jsfiddle.net/ss3d3/1/
Note: parseInt() can return NaN, so you may want to add code to check the return value.
Late answer, but you could always use the double bitwise NOT ~~ trick:
~~'-77.230202' // -77
~~'77.230202' // 77
~~'-77.990202' // -77
~~'77.930202' // 77
No octal concerts with this method either.
try this, but you'd have to convert your number to a string.:
var reg = /^-?\d{2}/,
num = -77.49494;
console.log(num.toString().match(reg))
["-77"]
var num = -77.230202;
var integer = num < 0 ? Math.ceil(num) : Math.floor(num);
Also see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math.
Do you just want to return everything to the left of the decimal point? If so, and if these are strings as you say, you can use split:
var mystring = -77.230202;
var nodecimals = mystring.split(".", 1);

Categories

Resources