Viewed   53 times

Could anyone give me an explanation (and maybe an example) on how to strip the trailing zeros from a number using PHP.

For example:

"Lat":"37.422005000000000000000000000000","Lon":"-122.84095000000000000000000000000"

Would be turned in to:

"Lat":"37.422005","Lon":"-122.84095"

I am trying to strip the zeros to make it more readable. I tried using str_replace() but this replaced the zeros inside the number too.

 Answers

4

Forget all the rtrims, and regular expressions, coordinates are floats and should be treated as floats, just prepend the variable with (float) to cast it from a string to a float:

$string = "37.422005000000000000000000000000";
echo (float)$string;

output:

37.422005

The actual result you have are floats but passed to you as strings due to the HTTP Protocol, it's good to turn them back into thier natural form to do calculations etc on.

Test case: http://codepad.org/TVb2Xyy3

Note: Regarding the comment about floating point precision in PHP, see this: https://.com/a/3726761/353790

Monday, October 17, 2022
4

You need a Ajax call to pass the JS value into php variable

JS Code will be (your js file)

var jsString="hello";
$.ajax({
    url: "ajax.php",
    type: "post",
    data: jsString
});

And in ajax.php (your php file) code will be

$phpString = $_POST['data'];     // assign hello to phpString 
Thursday, November 10, 2022
 
2

alert('my name is: <?php echo $man; ?>' );

Friday, August 19, 2022
 
2

Use DecimalFormat

  double answer = 5.0;
   DecimalFormat df = new DecimalFormat("###.#");
  System.out.println(df.format(answer));
Saturday, October 1, 2022
 
3

If you want to view your Score data as text, with no trailing zeroes, then use:

df_view <- df[c("Gene", "Score")]
df_view$Score <- sub("0+$", "", as.character(df_view$Score))

df_view

   Gene   Score
1  AAT2  15.401
2  ACB1  5.1188
3  ACF2  15.045
4 ADE16  3.0408
5 ADE17 0.28143
6  ADE4  19.792

Data:

df <- data.frame(Gene=c("AAT2", "ACB1", "ACF2", "ADE16", "ADE17", "ADE4"),
                 Score=c(15.40100, 5.11880, 15.04500, 3.04080, 0.28143, 19.79200),
                 stringsAsFactors=FALSE)
Wednesday, August 31, 2022
 
e-cloud
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :