Как убедиться, что добавлен только один десятичный разделитель? - PullRequest
0 голосов
/ 22 апреля 2020

каждый ...
Я только начал разработку в Cordova для Android. Я хотел разработать приложение для калькулятора, чтобы улучшить свои навыки, но мне кажется, что я здесь немного заблудился. Я сделал калькулятор с двумя дисплеями, несколькими операторами и цифровыми кнопками, очевидно, в HTML. Но я не могу понять, как реализовать десятичный разделитель. Сначала я подумал, что мог бы использовать переменную в качестве логического переключателя, но оказалось, что функция number () уничтожает. десятичный разделитель, прежде чем я смогу сбросить его на true. Ниже приведен образец html, а также GUI.

. Я думал о создании новой переменной с именем var isExist, которая может сканировать, существует ли десятичное число или нет, и затем работать.

Но в любом случае код приведен ниже.

Не использовал JSFiddle, потому что, похоже, что подобные службы не работают в моем регионе

введите описание изображения здесь

<html>
    <head>
        <link rel="stylesheet" href="css/index.css">
        <style type="text/css">
            @font-face{
            font-family: josefin-sans light;
            src: url(font/static/JosefinSans-Light.ttf);
            }       
        </style>
    </head>
    <body>
        <div id="mySidenav" class="sidenav">      
            <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
            <a href="#">About</a>
            <a href="#">Services</a>
            <a href="#">Clients</a>
            <a href="#">Contact</a>
        </div>
        <div id="swipe-area"></div>
        <span id= "menu" onclick="openNav()">&nbsp;&#9776;</span>
        <span id="title">Calculator</span>
        <div id="calc">
            <table>
                <tr rowspan="2" id="display">
                    <th colspan="4">
                        <p id="prev"></p>
                        <p id="curr"></p>
                    </th>
                </tr>
                <tr class="keyboard">
                    <th><input type="button" class="operator" id="clear" value="C"></th>
                    <th><input type="button" class="operator" id="backspace" value=&larr;></th>
                    <th><input type="button" class="operator" id="invert" value=&plusmn;></th>
                    <th><input type="button" class="operator" id="/" value=&div;></th>
                </tr>
                <tr class="keyboard">
                    <th><input type="button" class="number" id="7" value="7"></th>
                    <th><input type="button" class="number" id="8" value="8"></th>
                    <th><input type="button" class="number" id="9" value="9"></th>
                    <th><input type="button" class="operator" id="*" value=&times;></th>
                </tr>
                <tr class="keyboard">
                    <th><input type="button" class="number" id="4" value="4"></th>
                    <th><input type="button" class="number" id="5" value="5"></th>
                    <th><input type="button" class="number" id="6" value="6"></th>
                    <th><input type="button" class="operator" id="-" value=&minus;></th>
                </tr>
                <tr class="keyboard">
                    <th><input type="button" class="number" id="1" value="1"></th>
                    <th><input type="button" class="number" id="2" value="2"></th>
                    <th><input type="button" class="number" id="3" value="3"></th>
                    <th><input type="button" class="operator" id="+" value=&plus;></th>
                </tr>
                <tr class="keyboard">
                    <th></th>
                    <th><input type="button" class="number" id="0" value="0"></th>
                    <th><input type="button" class="operator" id="." value=&dot;></th>
                    <th><input type="button" class="operator" id="=" value=&equals;></th>
                </tr>
            </table>
        </div>
    </body>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript" src="js/jQuery.js"></script>
    <script type="text/javascript" src="js/jquery.touchSwipe.min.js"></script>
    <script type="text/javascript" src="js/swipe.js"></script>
</html>
function openNav(){//ignore this
    document.getElementById("mySidenav").style.width ="100%";
}

function closeNav(){//ignore this too
    document.getElementById("mySidenav").style.width ="0px";
}

function getPrevious(){//gets the value for top display
    return document.getElementById("prev").innerText;
}

function setPrevious(num){//sets the value for top display
    document.getElementById("prev").innerText=num;
}

function getCurrent(){//gets the value for bottom display
    return document.getElementById("curr").innerText;
}

function setCurrent(num){//sets the value for bottom display
    if(num==""){
        document.getElementById("curr").innerText=num;
    }
    else{
    document.getElementById("curr").innerText=getFormattedNumber(num)+symbol;
    symbol="";
    }
}

function getFormattedNumber(num){//formats number into indian numeral system
    var n = Number(num);
    var value = n.toLocaleString("hi-IN");
    return value;
}

function reverseNumber(num){//extract number from here
    return Number(num.replace(/,/g,''));
}

//catch operation of operator from here

var operator = document.getElementsByClassName("operator");
var rep=true;//---->this is the switch to enable decimal button(not functional)
var del;
for(var i=0;i<operator.length;i++){
    operator[i].addEventListener("click",function(){
        if(this.id=="clear"){
            setPrevious("");
            setCurrent("");
        }
        else
        if(this.id=="backspace"){
            var output=reverseNumber(getCurrent()).toString();
            if(output){
                del=output.charAt(output.length-1);//I am sure the code went wrong here
                if(del=="."){
                    rep=true;
                }
                output=output.substr(0,output.length-1);
                setCurrent(output);
            }
        }
        else
        if(this.id=="invert"){
            var output=reverseNumber(getCurrent());
            if(output!=""){
                output=-output;
                setCurrent(output);
            } 
        }
        else
        if(this.id=="."){//this is probably WHERE YOU WANT TO CHECK
            var output=reverseNumber(getCurrent()).toString();
            if(output!=""){
                if(rep==true){
                    symbol=this.id;
                    output=output
                    setCurrent(output);
                    rep=false;
                }
            }
        }
        else{
            var current=getCurrent();
            var previous=getPrevious();
            if(output=="" && history!=""){
                if(isNaN(history[history.length-1])){
                    history=history.substr(0,history.length-1);
                }
            }
            //code is incomplete here , ignore it
        }
    })
}

var number = document.getElementsByClassName("number");
for(var i=0;i<number.length;i++){
    number[i].addEventListener("click",function(){
        var output=reverseNumber(getCurrent());
        if(output!=NaN){
            if(getCurrent().charAt(getCurrent().length-1)=="."){
                output=output+(0.1*this.id)
                setCurrent(output);
            }
            else{
            output=output+this.id;
            setCurrent(output);
            }
        }
    })
}
body{
    margin: 0px;
    background: linear-gradient(to left top,rgb(99, 99, 255),rgb(126, 197, 255));
    font-family: josefin-sans light;
}

.sidenav{
    height: 100%;
    width: 0%;
    position:fixed;
    z-index: 1;
    top:0;
    left: 0;
    background-color: rgb(255, 255, 255);
    overflow-x: hidden;
    padding-top: 60px;
    transition: 0.5s;
}

.sidenav a{
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: 25px;
    color: rgb(132, 132, 255);
    display: block;
    transition: 0.3s;
}

.sidenav a:hover{
    color: #000000;
    font-size: 230%;
}

.sidenav .closebtn{
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px;
    margin-left: 50px;
}

.sidenav .closebtn:hover{
    color: red;
}

#menu,#title{
    font-size: 250%;
    color: white;
}

#title{
    position: absolute;
    left: 50%;
    top: 3%;
    z-index: 0;
    transform: translate(-50%,-50%);
}

#main{
    transition: margin-left .5s;
    padding: 20px;
}

@media screen and (max-height:450px){
    .sidenav{ padding-top: 15px;}
    .sidenav a{font-size: 18px;}
}

::-webkit-scrollbar{
    height: 5px;
}

::-webkit-scrollbar-thumb{
    background: rgb(223, 223, 223);
    border-radius: 10px;
}

table{
    margin: auto;
    text-align: center;
    border-spacing: 0 15px;
    padding: 10px;
    table-layout: fixed;
}

input[type=button]{
    border: none;
    outline: none;
    border-radius: 100%;
    height: 100%;
    width: 100%;
    font-weight: 500;
    font-size:large;
}

#calc{
    background-color:rgba(240, 248, 255, 0.4);
}

#display{
    background-color: rgba(0, 0, 0, 0.4);
}

#prev,#curr{
    max-width: 326px;
    overflow: auto;
}

#prev{
    text-align: right;
    font-size: 150%;
    margin: 0px 0px 0px 0px;
}

#curr{
    text-align: right;
    font-size: 400%;
    margin: 0px 0px 0px 0px;
}

#display{
    height: 150px;
}

tr.keyboard th{
    min-width: 80px;
    height: 80px;
}

#\/{
    background-color: aquamarine;
}

#\/:active{
    transition: 0.2s;
    font-size: medium;
    width: 80%;
    height: 80%;
}

#\*{
    background-color: lightsalmon;
}

#\*:active{
    transition: 0.2s;
    font-size: medium;
    width: 80%;
    height: 80%;
}


#\+{
    background-color: cornflowerblue;
}

#\+:active{
    transition: 0.2s;
    font-size: medium;
    width: 80%;
    height: 80%;
}

#\-{
    background-color: lightpink;
}

#\-:active{
    transition: 0.2s;
    font-size: medium;
    width: 80%;
    height: 80%;
}

#\={
    background-color: rgb(252, 250, 164);
}

#\=:active{
    transition: 0.2s;
    font-size: medium;
    width: 80%;
    height: 80%;
}

#clear,#backspace,#\.,#\37,#\38,#\39,#\34,#\35,#\36,#\31,#\32,#\33,#\30,#invert{
    background-color: rgb(234, 238, 255);
}

#clear:active,#backspace:active,#\.:active,#\37:active,#\38:active,#\39:active,#\34:active,#\35:active,#\36:active,#\31:active,#\32:active,#\33:active,#\30:active,#invert:active{
    transition: 0.2s;
    font-size: medium;
    width: 80%;
    height: 80%;
}

.swipe-area {
    position: absolute;
    width: 15px;
    left: 0;
    top: 0;
    height: 100%;
    background: #f3f3f300;
    z-index: 1;
}

Пожалуйста, прости меня за то, что я не предоставляю онлайн-версию

Ответы [ 2 ]

0 голосов
/ 22 апреля 2020

Хорошо, так что я понял это !!!

var symbol="";
function openNav(){
    document.getElementById("mySidenav").style.width ="100%";
}

function closeNav(){
    document.getElementById("mySidenav").style.width ="0px";
}

function getPrevious(){
    return document.getElementById("prev").innerText;
}

function setPrevious(num){
    document.getElementById("prev").innerText=num;
}

function getCurrent(){
    return document.getElementById("curr").innerText;
}

function setCurrent(num){
    if(num==""){
        document.getElementById("curr").innerText=num;
    }
    else{
    document.getElementById("curr").innerText=getFormattedNumber(num)+symbol;
    symbol="";
    }
}

function getFormattedNumber(num){
    var n = Number(num);
    var value = n.toLocaleString("hi-IN");
    return value;
}

function reverseNumber(num){
    return Number(num.replace(/,/g,''));
}

var operator = document.getElementsByClassName("operator");
var rep=true;
var del;
for(var i=0;i<operator.length;i++){
    operator[i].addEventListener("click",function(){
        if(this.id=="clear"){
            setPrevious("");
            setCurrent("");
        }
        else
        if(this.id=="backspace"){
            var output=reverseNumber(getCurrent()).toString();
            if(output){
                output=output.substr(0,output.length-1);
                alert(output);
                if(output.charAt(output.length-1)=="."){//THIS IS WHERE I MADE THE CHANGES!!!!
                    rep=true;
                }
                setCurrent(output);
            }
        }
        else
        if(this.id=="invert"){
            var output=reverseNumber(getCurrent());
            if(output!=""){
                output=-output;
                setCurrent(output);
            } 
        }
        else
        if(this.id=="."){
            var output=reverseNumber(getCurrent()).toString();
            if(output!=""){
                if(rep==true){
                    symbol=this.id;
                    output=output
                    setCurrent(output);
                    rep=false;
                }
            }
        }
        else{
            var current=getCurrent();
            var previous=getPrevious();
            if(output=="" && history!=""){
                if(isNaN(history[history.length-1])){
                    history=history.substr(0,history.length-1);
                }
            }
            //write continutation here
        }
    })
}

var number = document.getElementsByClassName("number");
for(var i=0;i<number.length;i++){
    number[i].addEventListener("click",function(){
        var output=reverseNumber(getCurrent());
        if(output!=NaN){
            if(getCurrent().charAt(getCurrent().length-1)=="."){
                output=output+(0.1*this.id)
                setCurrent(output);
            }
            else{
            output=output+this.id;
            setCurrent(output);
            }
        }
    })
}

Спасибо вам всем!

0 голосов
/ 22 апреля 2020

.toFixed(2) даст вам строку с вашим десятичным знаком.

var numbers = [
    123456,
    1234.56,
    12345.6
];

numbers.map((item)=>{console.log(item.toFixed(2))});
// 123456.00
// 1234.56
// 12345.60
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...