Separate the string value

Asked

Viewed 79 times

4

Colleagues.

When calculating the cart freight, it is returning as follows:

inserir a descrição da imagem aqui

I wonder, how do I get only the value 24.90? Because I need to add to the value of the cart. See below the reference codes:

PHP

$parametros = http_build_query($parametros);
    $url = 'http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx';
    $curl = curl_init($url.'?'.$parametros);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $dados = curl_exec($curl);
    $dados = simplexml_load_string($dados);

    foreach($dados->cServico as $linhas) {
        if($linhas->Erro == 0) {
            echo str_replace(",",".",$linhas->Valor) .'</br>';
            echo "<strong>Prazo de entrega:</strong> ".$linhas->PrazoEntrega. "Dias </br>";
        }else {
            echo $linhas->MsgErro;
        }

JQUERY

ajax1.onreadystatechange = function() {
        if (ajax1.readyState == 4) {
           document.getElementById("result").innerHTML = ajax1.responseText;
           valorFrete = document.getElementById("result").innerHTML;

           vv = document.getElementById("total").innerHTML + valorFrete;
           valorTotal = document.getElementById("total").innerHTML = vv.toFixed(2);

        } else {
            document.getElementById("result").innerHTML = "Aguarde, calculando...";
        }
    }

2 answers

7


Do it on the client side (no js), you can just do it:

responseText = '24.95, <strong> Outro texto, </strong>'; // faz de conta
valorFrete = parseFloat(responseText)
alert(valorFrete);

This way you already have the numerical value, ready for mathematical operations.

Note that this only works if you are sure that the first character will always be a digit.

4

You can break the string comma in this case, and take the first index:

let texto = '24.95, <strong> Outro texto, </strong>';
let valor = texto.split(',');
console.log(valor[0]);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.