Hueykareemliz's Profile

235
Points

Questions
45

Answers
40

  • There are two main ways to convert a string to a number in javascript. One way is to parse it and the other way is to change its type to a Number. All of the tricks in the other answers (e.g. unary plus) involve implicitly coercing the type of the string to a number. You can also do the same thing explicitly with the Number function.

    Parsing

    var parsed = parseInt("97", 10); 

    parseInt and parseFloat are the two functions used for parsing strings to numbers. Parsing will stop silently if it hits a character it doesn’t recognise, which can be useful for parsing strings like "92px", but it’s also somewhat dangerous, since it won’t give you any kind of error on bad input, instead you’ll get back NaN unless the string starts with a number. Whitespace at the beginning of the string is ignored. Here’s an example of it doing something different to what you want, and giving no indication that anything went wrong:

    var widgetsSold = parseInt("97,800", 10); // widgetsSold is now 97 

    It’s good practice to always specify the radix as the second argument. In older browsers, if the string started with a 0, it would be interpreted as octal if the radix wasn’t specified which took a lot of people by surprise. The behaviour for hexadecimal is triggered by having the string start with 0x if no radix is specified, e.g. 0xff. The standard actually changed with ecmascript 5, so modern browsers no longer trigger octal when there’s a leading 0 if no radix has been specified. parseInt understands radixes up to base 36, in which case both upper and lower case letters are treated as equivalent.

    Changing the Type of a String to a Number

    All of the other tricks mentioned above that don’t use parseInt, involve implicitly coercing the string into a number. I prefer to do this explicitly,

    var cast = Number("97"); 

    This has different behavior to the parse methods (although it still ignores whitespace). It’s more strict: if it doesn’t understand the whole of the string than it returns NaN, so you can’t use it for strings like 97px. Since you want a primitive number rather than a Number wrapper object, make sure you don’t put new in front of the Number function.

    Obviously, converting to a Number gives you a value that might be a float rather than an integer, so if you want an integer, you need to modify it. There are a few ways of doing this:

    var rounded = Math.floor(Number("97.654"));  // other options are Math.ceil, Math.round var fixed = Number("97.654").toFixed(0); // rounded rather than truncated var bitwised = Number("97.654")|0;  // do not use for large numbers 

    Any bitwise operator (here I’ve done a bitwise or, but you could also do double negation as in an earlier answer or a bitshift) will convert the value to a 32bit integer, and most of them will convert to a signed integer. Note that this will not do want you want for large integers. If the integer cannot be represented in 32bits, it will wrap.

    ~~"3000000000.654" === -1294967296 // This is the same as Number("3000000000.654")|0 "3000000000.654" >>> 0 === 3000000000 // unsigned right shift gives you an extra bit "300000000000.654" >>> 0 === 3647256576 // but still fails with larger numbers 

    To work correctly with larger numbers, you should use the rounding methods

    Math.floor("3000000000.654") === 3000000000 // This is the same as Math.floor(Number("3000000000.654")) 

    Bear in mind that coeercion understands exponential notation and Infinity, so 2e2 is 200 rather than NaN, while the parse methods don’t.

    Custom

    It’s unlikely that either of these methods do exactly what you want. For example, usually I would want an error thrown if parsing fails, and I don’t need support for Infinity, exponentials or leading whitespace. Depending on your usecase, sometimes it makes sense to write a custom conversion function.

    Always check that the output of Number or one of the parse methods is the sort of number you expect. You will almost certainly want to use isNaN to make sure the number is not NaN (usually the only way you find out that the parse failed).

    • 1043 views
    • 27 answers
    • 0 votes
  • Asked on July 16, 2020 in CSS.

    when you set display: grid; it means the children of this node are arranged using grid. It doesn’t set the div’s height or width for you. You need to set it if you want to contain it.

    There are multiple ways to set the width.

    1. You can use the grid the same way you’ve used for container. Like this,
    .container {   display: grid;   grid-template: 1fr / 80px 1fr; }  .content-1 {   background-color: red; }  .content-2 {   background-color: blue; }
    <div class="container">   <div class="content-1">Content 1</div>   <div class="content-2">Content 2</div> </div>

    1. You can contain both the appbar and the content in a flex, and set the flex-grow of container to 1.
    .app{   display: flex; }  .appbar{ flex-grow: 0; }  .main-container{ flex-grow: 1; } 

    or,

    use CSS calc for container like this.

    .analytics-grid {   display: grid;   grid-template-rows: auto;   grid-template-columns: 1fr 1fr;   row-gap: 10px;   column-gap: 10px;   grid-template-areas: "conversion conversion-daily";   width: calc(100vw - <appbar width>); } 

    PS: grid-template is short hand to set both row and columns at a time. Refer https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template

    • 381 views
    • 1 answers
    • 0 votes
  • Asked on July 16, 2020 in CSS.

    Image-thumbnail class use in img tag not in the div

    • 285 views
    • 4 answers
    • 0 votes
  • Asked on July 16, 2020 in CSS.

    Just set background property also with left and top based on Math.random() > 0.5 or not:

    $('#test').click(function() {       var docHeight = $(document).height(),         docWidth = $(document).width(),         $div = $('#test'),         divWidth = $div.width(),         divHeight = $div.height(),         heightMax = docHeight - divHeight,         widthMax = docWidth - divWidth;            $div.css({         left: Math.floor( Math.random() * widthMax ),         top: Math.floor( Math.random() * heightMax ),         background: Math.random() > 0.5 ? 'red' : 'green', // setting background here       });     });
    #test {     position:absolute;     height: 55px;   width: 55px;   background-color: red;   border-radius: 50%;   display: inline-block;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <div id="test"></div>

    • 302 views
    • 2 answers
    • 0 votes
  • Asked on July 16, 2020 in CSS.

    This took me a bit longer to figure out than I am proud to admit but here it is.

    The first div .carousel-item in a carousel needs to also have the active class. Otherwise the carousel has nowhere to start from.

    • 282 views
    • 1 answers
    • 0 votes
  • Asked on July 16, 2020 in CSS.

    2020 answer

    CSS Filter works on all current browsers

    To change any SVGs color

    1. Add the SVG image using an <img> tag.
    <img src="dotted-arrow.svg" class="filter-green"/> 
    1. To filter to a specific color, use the following Codepen(Click Here to open codepen) to convert a hex color code to a CSS filter:

    For example, output for #00EE00 is

    filter: invert(42%) sepia(93%) saturate(1352%) hue-rotate(87deg) brightness(119%) contrast(119%); 
    1. Add the CSS filter into this class.
        .filter-green{         filter: invert(48%) sepia(79%) saturate(2476%) hue-rotate(86deg) brightness(118%) contrast(119%);     } 
    • 774 views
    • 17 answers
    • 0 votes
  • Try using the vertical-align property for your columns. That should solve your problem.

    • 321 views
    • 1 answers
    • 0 votes
  • Asked on July 16, 2020 in CSS.

    Set the SVG color to white. The background-color to blue and give it a border-radius of 50%.

    • 303 views
    • 2 answers
    • 0 votes
  • Asked on July 16, 2020 in CSS.

    If you are going to use grid then you need to add that property. Very basic example what may help you is this:

    #mydiv {   display: grid;   justify-content: end; //your old properties   grid-column-start: 250;   grid-column-end:300; } 

    Anyway taking into account that for grid it is better to specify rows/cols.

    • 316 views
    • 2 answers
    • 0 votes
  • Asked on July 16, 2020 in Python.

    First using pd.to_datetime convert the Date column to pandas datetime series, then use Series.map to map the Quarter column to pd.offsets.QuarterEnd and subtract it from Date to get the desired results:

    df['Date'] = pd.to_datetime(df['Date']) df['QDate'] = df['Date'] - df['Quarter'].map(pd.offsets.QuarterEnd) 

    Result:

      Firm       Date  Quarter      QDate 0    A 2019-06-30        0 2019-06-30 1    A 2019-06-30        1 2019-03-31 2    A 2019-06-30        2 2018-12-31 3    A 2019-06-30        3 2018-09-30 4    B 2017-06-30        0 2017-06-30 5    B 2017-06-30        1 2017-03-31 6    B 2017-06-30        2 2016-12-31 7    B 2017-06-30        3 2016-09-30 
    • 279 views
    • 1 answers
    • 0 votes