# Converting byte array or String to float

**URL:** https://discourse.processing.org/t/converting-byte-array-or-string-to-float/27863
**Category:** Libraries
**Created:** [February 16, 2021, 10:51am UTC](https://discourse.processing.org/t/converting-byte-array-or-string-to-float/27863 "2021-02-16T10:51:01Z")
**Posts on this page:** 7
**Page:** 1

<div class="post-metadata">

### Author: ![TanviM](https://avatars.discourse-cdn.com/v4/letter/t/45deac/32.png) [@TanviM](https://discourse.processing.org/u/TanviM)
#### Post date: [February 16, 2021, 10:51am UTC](https://discourse.processing.org/t/converting-byte-array-or-string-to-float/27863/1 "2021-02-16T10:51:01Z")

</div>

Hi,  
**I have been successful in getting serial data** using this - [GitHub - p5-serial/p5.serialport: Serial Port API and Server for p5.js](https://github.com/p5-serial/p5.serialport#examples) library as either byte array or string values.

But when I tried converting string to float type using float() – I get a lot of NaN values which shouldn’t be coming since data is numerical.

Alternatively, I then tried getting data from serial port as byte array. I can’t find a way to convert this array to my original float value in P5.js.

**Any ideas on how to convert byte array to float or avoid getting NaN when converting string to float?**

Appreciate your time and help. Thanks.

I have used following methods:

1. From String to Float

```auto
let incomingData;

let dataValue;

incomingData = serial.readStringUntil('\n').trim();

dataValue = float(incomingData); //standard method in P5.js -- returns NaN values

```

I also tried parseFloat() – [JavaScript parseFloat() Function - GeeksforGeeks](https://www.geeksforgeeks.org/javascript-parsefloat-function/)

```auto
 dataValue = parseFloat(incomingData);
  //again returns maximum values as NaN

```

1. From Byte array to float

```auto
let incomingBytes = [];

let dataValue;

incomingBytes = serial.readBytesUntil('\n');

dataValue = dataView.getFloat64(bytebuffer); 
// This javascript method is not supported by P5.js it seems

```

Picture illustrates original float values that I am trying to get from serial port.

 ![HOr7d](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/a/aec5852a063f84ca552ecf13fdc6bf8fb62b7bcb.png)

---

<div class="post-metadata">

### Author: ![SNICKRS](https://avatars.discourse-cdn.com/v4/letter/s/43a26b/32.png) [@SNICKRS](https://discourse.processing.org/u/SNICKRS)
#### Post date: [February 16, 2021, 1:25pm UTC](https://discourse.processing.org/t/converting-byte-array-or-string-to-float/27863/2 "2021-02-16T13:25:37Z")

</div>

In processing, to turn a string into a float, you use `Float.parseFloat()`. I don’t know the variant of this in p5, but maybe you can find it.

---

<div class="post-metadata">

### Author: ![TanviM](https://avatars.discourse-cdn.com/v4/letter/t/45deac/32.png) [@TanviM](https://discourse.processing.org/u/TanviM)
#### Post date: [February 17, 2021, 5:39am UTC](https://discourse.processing.org/t/converting-byte-array-or-string-to-float/27863/3 "2021-02-17T05:39:45Z")

</div>

Its float() or parseFloat(). I have tried both.  
Also, if I do this conversion in serialEvent – the NaN returns are much more than when I do it in draw(). I am not sure why.

---

<div class="post-metadata">

### Author: ![erkosone](https://avatars.discourse-cdn.com/v4/letter/e/ba9def/32.png) [@erkosone](https://discourse.processing.org/u/erkosone)
#### Post date: [February 17, 2021, 6:36am UTC](https://discourse.processing.org/t/converting-byte-array-or-string-to-float/27863/4 "2021-02-17T06:36:37Z")

</div>

In my experience, this is the best way to get data from serial/BT\_serial port on PC…

```auto
try{
            if(mmInStream.available()>0){
                bytes = mmInStream.read(buffer);
                String s = new String(buffer, 0, bytes);
                dataStr += s;
                
                // check if last char are nl..
                if(dataStr.charAt(dataStr.length()-1) == nl){
                    String[] list = split(dataStr, nl);
                    for(String rcv_str : list){
                        if(rcv_str.length()>0){ // last string are void..
                            serialEvent(rcv_str); // call serialEvent() with parsed plc data..
                        }
                    }
                    dataStr = "";
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }

```

And this is the event function, works perfectly 😉

```auto
void serialEvent(String str){
    println("From PLC:", str);
    if(str.equals(sn)){
        //..
    }
}

```

` char nl = '#';`

---

<div class="post-metadata">

### Author: ![erkosone](https://avatars.discourse-cdn.com/v4/letter/e/ba9def/32.png) [@erkosone](https://discourse.processing.org/u/erkosone)
#### Post date: [February 17, 2021, 6:40am UTC](https://discourse.processing.org/t/converting-byte-array-or-string-to-float/27863/5 "2021-02-17T06:40:23Z")

</div>

La cosa es sencilla… leer bytes en un buffer hasta recibir un char concreto, tras recibirlo hay que mirar si han llegado mas de una secuencia de datos y hacer un split() usando ese mismo char… y luego enviar los datos a la función del evento.

Esto lo he preparado para Bluetoth en processing 3.4.5 y funciona muy bien con dispositivos como Arduino o raspberry pi

---

<div class="post-metadata">

### Author: ![TanviM](https://avatars.discourse-cdn.com/v4/letter/t/45deac/32.png) [@TanviM](https://discourse.processing.org/u/TanviM)
#### Post date: [February 18, 2021, 5:37am UTC](https://discourse.processing.org/t/converting-byte-array-or-string-to-float/27863/6 "2021-02-18T05:37:10Z")

</div>

This is a processing (or java based) code. I have done this on processing before. But now I have to make a switch to P5.js for running my program in a web browser.

I have tried implementing try and catch as well. Doesn’t work.  
When I print the incoming string type data – everything seems to look fine. But when I convert string to float; NaN values come up that shouldn’t be there.

---

<div class="post-metadata">

### Author: ![TanviM](https://avatars.discourse-cdn.com/v4/letter/t/45deac/32.png) [@TanviM](https://discourse.processing.org/u/TanviM)
#### Post date: [February 18, 2021, 7:29am UTC](https://discourse.processing.org/t/converting-byte-array-or-string-to-float/27863/7 "2021-02-18T07:29:21Z")

</div>

As seen in the last image, there were empty strings or null values coming. I just had to put a check for it before doing the conversion.

Thanks to all the commenters.

```
 let incomingData; //incoming serial value is stored in this variable

 let temparray = [1000]; //temporary array used in updating final array

 let plot_from_here = [1000]; //final array of values to plot
 function setup(){}
 function draw(){}

 function serialEvent() {

  if(serial.available()>0){

   incomingData = serial.readStringUntil('\n'); //read string until next line

    if(incomingData != ""){

     incomingData = trim(incomingData); //trim white spaces

     arrayCopy(temparray,0, temparray,1,999); //Copy value from index 0 to index 1

     temparray[0]= float(incomingData); //Update index 0 of temparray for the incoming value -- the value is converted to float from string type

     plot_from_here = temparray; //update values in final array

    print(plot_from_here);

     }
   }
  }
```
