Greater part of decimal number in js - javascript

I have this problem:
Write a function greaterpart that receives a decimal number. The number should be greater than zero.
The function is required to identify the bigger part of the decimal number, whether it’s the integer or
the fractional part, and then alert the bigger part.
For example:
greaterpart(32.45) alerts 45.
and
greaterpart(301.71) alerts 301.
And this is my solution:
function graterpart(x){
if(x<0){
alert("Number can not be null");
}
else{
var x;
var y;
y= parseFloat(x);
var remainder = (y-Math.floor(y))*10000;
if(y>remainder){
alert(y);
} else{
alert(remainder);
}
}
}
graterpart(32.45);
But it is not working as it should be.
What am I doing wrong here? Thanks in advance.

Try this:
<script>
function greaterpart(x){
alert(Math.max.apply(this, x.toString().split('.')));
}
greaterpart(32.45);
</script>
Math.max() will implicitely convert the strings returned by String.prototype.split() into numbers.
If you don't understand the function reformulate it with distinct steps:
Turn the number into a string:
x = x.toString();
Split it at the decimal point:
var parts = x.split('.'); // Is now ["32", "45"]
Get the maximum value:
var greater = Math.max(parts[0], parts[1]);
But there is a shorter way. Keep this in mind:
var result1 = fun(arg1, arg2, arg3);
var result2 = fun.apply(thisValue, [arg1, arg2, arg3]);
The second line looks a little convoluted but does exactly the same as the first. You can use this now to simplify the call to Math.max():
var greater = Math.max.apply(this, parts);
And now output it with console.log() or alert().

Simple convert it to string split by . get two element array parseInt each and compare simplest of all
var s = 56.69;
//console.log(s.toString())
var d = s.toString().split(".");
var greater = (parseInt(d[0],10) > parseInt(d[1],10)) ? d[0] : d[1];
alert(greater);

I think the best will be to convert your decimal to string and then split it by ".", convert both parts to integer and alert the greater part.
function graterpart(x){
if(x < 0){
alert("Number can not be null");
}else{
var str = x.toString();
if(str.indexOf(".") != -1){
var parts = str.split(".");
var first_part = parseInt(parts[0]);
var second_part = parseInt(parts[1]);
alert(Math.max(first_part, second_part));
}else{
alert(x);
}
}
}
graterpart(321.45);
https://jsfiddle.net/x7on7xjk/

It can simply be done like this:
var number = 312.25;
var numberStr = number.toString();
var twoParts = numberStr.split(".");
if ((parseInt(twoParts[0])) > (parseInt(twoParts[1]))){
alert (twoParts[0]);
}else {
alert(twoParts[1]);
}

Related

How to make a single string into a multitude of strings?

I have a string called e3 which holds the string 1,2,4,5,3,6. I want to add up all of those numbers up to make the number 21 I was considering doing a for loop for this however I do not know how to turn part of a string into its own value.
I anyone has any better idea of what to do please comment, or answer.
You could use String#split for the string and use Array#reduce for summing.
var e3 = '1,2,4,5,3,6',
sum = e3.split(',').reduce(function (a, b) {
return a + +b; // +b forces b to number
}, 0);
console.log(sum);
If you are sure that it is always a comma separated list of numbers, you could split it on the comma into an array and then use array.reduce() to sum them
var asString = '1,2,4,5,3,6';
var asArray = asString.split(',');
var total = asArray.reduce(function(prev, current){
return prev + parseInt(current, 10);
}, 0);
console.log(total) // outputs 21;
You can do it like this:
var e3 = "1,2,4,5,3,6";
// Split by separator ','
var stringsArr = e3.split(',');
var sum = 0;
// Loop through array of string numbers
stringsArr.forEach(function(str) {
// get Int from a string
var strVal = parseInt(str, 10);
sum += strVal;
});
here's the fiddle
Here is working code to do what you need: https://plnkr.co/edit/8LSkZi0oC8msbHI0qOrz?p=preview
At first you use the split method - this separates a string into an array of strings, based on some separator value. In our case, the separator is a comma, but it could be a blank space or something else:
var testString = '1,2,4,5,3,6';
var separator = ',';
function splitStringOnCommasAndGetArray(string, separator){
var arrayOfStrings = string.split(separator);
return arrayOfStrings;
}
After that, we loop through the array and turn each value into a number. We add the numbers, like so:
function addUpArray(arrayOfStrings){
var totalNumber = 0;
for(var i = 0; i < arrayOfStrings.length; i++){
var currentNum = parseInt(arrayOfStrings[i]);
console.log(currentNum);
totalNumber += currentNum;
}
return totalNumber;
}

Reverse a number in javascript

I want to reverse a number t following the tutorial.First I have passed a number as a parameter. I have converted the number to string with to String function. Then I used split("").reverse().join("") to reverse the number.
My code is as follows:
<script type="text/javascript">
function reverse_the_string(num) {
num = String(num);
// str = num.toString;
num.split("").reverse().join("");
return;
}
console.log(reverse_the_string(56789));
</script>
However I get an error undefined? Can anyone explain what is the wrong?
You do not return the result. Use
return num.split("").reverse().join("");
If you use just return, then undefined is returned.
function reverse_the_string(num) {
return String(num).split("").reverse().join("");
}
document.write(reverse_the_string(56789));
Caveat: Reversing works only with small numbers!
Try this (Recursive Method)
function reverseNum(num) {
if(num == 0)return 0;
let x = Math.pow(10, (num + '').length - 1);
return (num % 10) * x + reverseNum(Math.floor(num / 10));
}
console.log(reverseNum(432));
The solution of casting the number into a string and reversing the string is a good solution, BUT it doesn't cover all the cases. There are 2 cases that need to be addressed:
Reversing a negative number it doesn't retain the sign.
Reversing a number that ends with zero(s), after reversing you will have leading zeros, e.g. 12300 the reverse will be "00321" when it should be "321".
Using Regular function
var reversed = parseFloat(num.toString().split("").reverse().join()) * Math.sign(num);
Using Arrow Function
var reversed = num => parseFloat(num.toString().split('').reverse().join('')) * Math.sign(num);
Convert the number variable to a string:
var n = 4557
n = n.toString();
then execute the below code.
//**Reverse the Number In javascript**
var result = "";
function reverseNumber(n){
// reverse the number via loop
for(var i=x.length-1; i>=0; i--){
result+=n[i];
}
return Number(result)
}
var x = prompt("Enter a number : ");
console.log(reverseNumber(x))
In order to reverse number/ string you can refer this method:
(without using slice() and substring() methods)
function reverse(str) {
var rev = "";
number = parseInt(str);
for (; number > 0;) {
rev += number % 10;
number = Math.floor(number / 10)
}
return rev;
}

Printing floating point values with decimals and not with e-notation in JavaScript

When i print a floating point like 0.0000001 in JavaScript it gives me
1e-7
how can i avoid that and instead print it "normally" ?
You can use this:
var x = 0.00000001;
var toPrint = x.toFixed(7);
This sets toPrint to a string representation of x with 7 digits to the right of the decimal point. To use this, you need to know how many digits of precision you need. You will also need to trim off any trailing 0 digits if you don't want them (say, if x was 0.04).
function noExponent(n){
var data= String(n).split(/[eE]/);
if(data.length== 1) return data[0];
var z= '', sign= +n<0? '-':'',
str= data[0].replace('.', ''),
mag= Number(data[1])+ 1;
if(mag<0){
z= sign + '0.';
while(mag++) z += '0';
return z + str.replace(/^\-/,'');
}
mag -= str.length;
while(mag--) z += '0';
return str + z;
}
I've got a simple solution that appears to be working.
var rx = /^([\d.]+?)e-(\d+)$/;
var floatToString = function(flt) {
var details, num, cnt, fStr = flt.toString();
if (rx.test(fStr)) {
details = rx.exec(fStr);
num = details[1];
cnt = parseInt(details[2], 10);
cnt += (num.replace(/\./g, "").length - 1); // Adjust for longer numbers
return flt.toFixed(cnt);
}
return fStr;
};
floatToString(0.0000001); // returns "0.0000001"
EDIT Updated it to use the toFixed (didn't think about it).
EDIT 2 Updated it so it will display numbers 0.0000000123 properly instead of chopping off and showing "0.00000001".

Javascript to test value against regex and later value if needed

in my webpage I have a total in currency format that can either be positive or negative.
Example $5.50 or $(5.50).
This value is nothing other than text contained within a span tag. I'm trying to read the value and convert it into a numeric value in js where I can then perform math calculations against it.
Example $5.50 -> 5.50 and $(5.50) -> -5.50
I have written the following regex script to handle converting negative currency values into numeric values
var regex = /^\$*?\((\d+(\.)?(\d+)?)\)$/
I have the following methods to handle retrieving and converting the value.
//retrieve value from template
$.fn.fieldVal = function () {
var val;
if ($(this).is(':input')) {
val = $(this).val();
} else {
val = $(this).text();
}
return convertCurrencyToNumeric(val);
};
//convert currency to numeric value
function convertCurrencyToNumeric(n) {
var regex = /^\$*?\((\d+(\.)?(\d+)?)\)$/
n = n.replace(/[^0-9-\.]/g, '');
if(isNumber(n)) {
n = parseFloat(n);
return n;
}
return 0;
}
//test if numeric
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
I'm not clear how to first test if the value is negative and secondly if negative, replace the value with regex outcome.
Note: Negating classes can really clear up regEx problems, IMO. And no, I don't care what JSLint's opinion on the matter is. Using '.' is slow and clumsy and the rationale given for that particular lint gotcha is absurd.
function convertCurrency(str){
var negMatch = ( str.match(/(^\$-|^-\$|^$\()/g) ), //handles -$5.05 or $-5.05 too
str = str.replace(/[^\d.]/g,''), //anything that's not a digit or decimal point
//gotcha, Europeans use ',' as a decimal point so there's a localization concern
num = parseFloat(str);
if(negMatch){ num *= -1; }
return num;
}
function getMoney (str) {
var amount = str.replace(/(\$)(\()?(\d+\.\d{0,2})\)?/,
function (match, dollar, neg, money) {
var negSign = neg ? "-" : "";
return negSign + money;
}
);
return parseFloat(amount);
}
var str1 = "$(5.50)";
var str2 = "$5.50";
console.log( getMoney(str1) );
console.log( getMoney(str2) );

Using parseFloat() or parseInt() and regex in JavaScript (converting a CSV file)

I'm converting a CSV file to a local 2D array. I wanted to know if there is a better way to convert strings to floats/int rather then using regex followed by a parseFloat() / parseInt.
Ideas / Suggestions?
// numex() - checkes to see if the string (str) is a number
// returns number.valid (true||false) and number.value = (float||int||string)
numex = function(str){
number = {};
number.valid = false;
number.value = str;
// if we see a number then convert it to a floating point or integer
if((number.value.search(/[^0-9^\.^\$^\%^\-^\"^,^ ]+/) < 0) && str.length > 0) {
number.valid = true;
number.value = str.replace(/[^\-^0-9^\.]+/g, ''); // TODO add % coversion code for example if we see a 10% covert it to .1
if(number.value.search(/[\.]/) >= 0) {
number.value = parseFloat(number.value); // replace floating point
} else {
number.value = parseInt(number.value); // replace integers
}
}
return number; // number.valid = true or false;
}
var num = numex("1.101");
alert(num.value);
I don't think you need to use regexp at all. Try this:
var num = {};
num.value = new Number(str);
num.valid = !isNaN(num.value);
Number constructor is more strict than parseInt and parseFloat in that it does not accept strings like 10aaa or 1.2bbb so there is no need to perform a regexp check.
I simplified the code greatly and used something similar to what LeZuse did.
isNaN(value) || value == ""
https://github.com/designpro/jCSV

Categories

Resources